Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use php callable to call constructor

Tags:

php

callable

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?

like image 842
Choraimy Avatar asked Sep 16 '25 06:09

Choraimy


2 Answers

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 );
like image 169
IMSoP Avatar answered Sep 17 '25 21:09

IMSoP


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'));
like image 28
laurent Avatar answered Sep 17 '25 19:09

laurent