Skip to content

PHP and callable class properties

PHP class properties can’t be type-hinted as callable, even though method parameters can be. Here’s what you can do to get around this limitation.

An orange gecko lies poised, posing toward the viewer.

This isn’t a bug but a language decision. There is an explanation as to why a callable as a class property isn’t allowed.

However, a class property can be a Closure type. The constructor can receive a type-hinted callable argument and make use of Closure::fromCallable() or First Class Callable syntax to convert as necessary.

If you need to make this property publicly accessible, a Closure is a callable and so a getter method returning a type-hinted callable is acceptable.

class Foo
{
  private Closure $bar;

  public function __construct(callable $baz)
  {
    $this->bar = $baz(...); // Equivalent to Closure::fromCallable($baz)
  }

  public function getBar(): callable
  {
    return $this->bar;
  }
}