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

Why Does This Happen?

Starting with PHP 8.2, the use of "static" in callables is deprecated, which means the following are no longer supported:

'static::method'
['static', 'method']

If you're using either of these in your PHP code, it will throw the following error:

Deprecated: Use of "static" in callables is deprecated

How to Fix the Issue?

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

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

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

class Calculator
{
  public function calculate(array $nums): array
  {
    // Deprecated: Use of "static" in callables is deprecated
    return array_map(['static', 'add'], $nums);
  }

  public static function add(int $num): int
  {
    return $num + 10;
  }
}

class AdvancedCalculator extends Calculator
{
  public static function add(int $num): int
  {
    return $num + 1;
  }
}

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

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

class Calculator
{
  public function calculate(array $nums): array
  {
    return array_map([static::class, 'add'], $nums);
  }

  public static function add(int $num): int
  {
    return $num + 10;
  }
}

class AdvancedCalculator extends Calculator
{
  public static function add(int $num): int
  {
    return $num + 1;
  }
}

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

As you can see in this example, late static binding is correctly applied, and no deprecation notice is shown.


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.