I am trying to call a class' constructor through a callable, so I had the following code:
$callable = array('Foo', '__construct');
However calling this will throw the following error:
Fatal error: Non-static method Foo::__construct() cannot be called statically
I understand that the constructor is not a static method, but I can't use an existing instance to call the constructor for a new instance (as it will just call the constructor on the existing object again), is there any way at all to call a constructor like this?
If you're looking for a simple way to dynamically choose which class to construct, you can use a variable name with the new
keyword, like so:
$inst = new $class_name;
// or, if the constructor takes arguments, provide those in the normal way:
$inst = new $class_name('foo', 'bar');
However, if what you need is a way of passing the constructor to something which is already expecting a callable, the best I can think of is to wrap it in an anonymous function:
$callable = function() { return new Foo; }
call_user_func( $callable );
Or using the short single-expression closure syntax introduced in PHP 7.4:
$callable = fn() => new Foo;
call_user_func( $callable );
If you really have to use call_user_func
, this might work, though it's not clear why you would want to do this:
$reflection = new ReflectionClass("Foo");
$instance = $reflection->newInstanceWithoutConstructor();
call_user_func(array($instance, '__construct'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With