How to Fix 'Use of "self" in callables is deprecated' PHP Error?

Why Does This Happen?

In PHP 8.2, the use of self in callables was deprecated, which means the following are no longer valid:

'self::method'
['self', 'method']

If you're using either of the above syntax, it will throw the following error:

Deprecated: Use of "self" in callables is deprecated

How to Fix the Issue?

Fixing this issue is very straightforward, you can simply replace "self" with self::class. This means, you would use the following:

self::class . '::method' // instead of 'self::method'
[self::class, 'method'] // instead of ['self', 'method']

For example, the following code will result in the deprecation notice:

class Calculator
{
  public function addOne(int $num): int
  {
    return $num + 1;
  }

  public function addOneToAll(array $nums): array
  {
    // Deprecated: Use of "self" in callables is deprecated
    return array_map(['self', 'addOne'], $nums);
  }
}

$calc = new Calculator();
var_dump($calc->addOneToAll([1, 2, 3, 4]));

You can fix this, for example, in the following way:

class Calculator
{
  public function addOne(int $num): int
  {
    return $num + 1;
  }

  public function addOneToAll(array $nums): array
  {
    return array_map([self::class, 'addOne'], $nums);
  }
}

$calc = new Calculator();
var_dump($calc->addOneToAll([1, 2, 3, 4])); // [2, 3, 4, 5]

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.