call_user_func_array passing arguments to a constructor
Solution 1
You can't call the constructor of $class
like this:
call_user_func_array (new $class, $args);
That's no valid callback as first parameter. Let's pick this apart:
call_user_func_array (new $class, $args);
Is the same as
$obj = new $class;
call_user_func_array ($obj, $args);
As you can see, the constructor of $class
has been already called before call_user_func_array
comes into action. As it has no parameters, you see this error message:
Missing argument 1 for Product::__construct()
Next to that, $obj
is of type object. A valid callback must be either a string or an array (or exceptionally a very special object: Closure
, but that's out of discussion here, I only name it for completeness).
As $obj
is an object and not a valid callback, so you see the PHP error message:
Object of class Product could not be converted to string.
PHP tries to convert the object to string, which it does not allow.
So as you can see, you can't easily create a callback for a constructor, as the object yet not exists. Perhaps that's why you were not able to look it up in the manual easily.
Constructors need some special dealing here: If you need to pass variable arguments to a class constructor of a not-yet initialize object, you can use the ReflectionClass
to do this:
$ref = new ReflectionClass($class);
$new = $ref->newInstanceArgs($args);
See ReflectionClass::newInstanceArgs
Solution 2
Not possible using call_user_func_array()
, because (as the name suggest) it calls functions/methods, but is not intended to create objects, Use ReflectionClass
$refClass = new ReflectionClass($class);
$object = $refClass->newInstanceArgs($args);
Another (more design-based) solution is a static factory method
class MyClass () {
public static function create ($args) {
return new self($args[0],$args[1],$args[2],$args[3],$args[4]);
}
}
and then just
$object = $class::create($args);
In my eyes it's cleaner, because less magic and more control
tuespetre
Updated on June 05, 2022Comments
-
tuespetre almost 2 years
I have searched many a page of Google results as well as here on stackoverflow but cannot find a solution that seems to fit my situation. I appear to have but one last snag in the function I am trying to build, which uses call_user_func_array to dynamically create objects.
The catchable fatal error I am getting is
Object of class Product could not be converted to string
. When the error occurs, in the log I get five of these (one for each argument):PHP Warning: Missing argument 1 for Product::__construct(),
before the catchable fatal error.This is the code of the function:
public static function SelectAll($class, $table, $sort_field, $sort_order = "ASC") { /* First, the function performs a MySQL query using the provided arguments. */ $query = "SELECT * FROM " .$table. " ORDER BY " .$sort_field. " " .$sort_order; $result = mysql_query($query); /* Next, the function dynamically gathers the appropriate number and names of properties. */ $num_fields = mysql_num_fields($result); for($i=0; $i < ($num_fields); $i++) { $fetch = mysql_fetch_field($result, $i); $properties[$i] = $fetch->name; } /* Finally, the function produces and returns an array of constructed objects.*/ while($row = mysql_fetch_assoc($result)) { for($i=0; $i < ($num_fields); $i++) { $args[$i] = $row[$properties[$i]]; } $array[] = call_user_func_array (new $class, $args); } return $array; }
Now, if I comment out the call_user_func_array line and replace it with this:
$array[] = new $class($args[0],$args[1],$args[2],$args[3],$args[4]);
The page loads as it should, and populates the table I am building. So everything is absolutely functional until I try to actually use my
$args
array withincall_user_func_array
.Is there some subtle detail about calling that array that I am missing? I read the PHP manual for call_user_func_array once, and then some, and examples on that page seemed to show people just building an array and calling it for the second argument. What could I be doing wrong?
-
tuespetre over 12 yearsThank you for your answer, however, I am not getting a 'no valid callback' error, and the error log seemingly indicates that the
call_user_func_array
does successfully call the construct, because it gives me aPHP Warning: Missing argument 1 for Product::__construct()
for each of the five arguments the particular constructor is expecting but for some reason not receiving. Of course, it may be something I do not yet understand, but that is the knowledge I possess so far. -
hakre over 12 yearsYou first instantiate the object with
new $class
. That means the constructor has been already called beforecall_user_func_array
get's into action. You see? First comesnew
because you use it as an expression in the parameter, then the function call happens. But because of new being executed, the constructor of$class
is already called (with no arguments). And then PHP tries to convert the object into a string because the first parameter expects a string or array. Because your object does not support casting to strings, you get the error/warning. -
tuespetre over 12 yearsI see! Thank you. I will look into other ways of dynamically passing arguments to a constructor.
-
hakre over 12 years@tuespetre: See the code example in the answer (the two lines of code at the end), that is the way you can do that.
-
tuespetre over 12 yearsYou mean you can call, for instance
Product::__construct($args)
where$args
is an array of arguments? Can all functions be called using an argument array like that? -
KingCrunch over 12 yearsWhere did I say something like that?!? Of course you can instanciate objects with arrays, but then you'll receive that array as single argument in the constructor. It doesn't look like thats what you want
-
tuespetre over 12 yearsSorry, I misread your post. :)
-
tuespetre over 12 yearsI understand this ReflectionClass thing now. I want to thank you very much for answering. I can now do what i need!
-
demonkoryu about 9 yearsThe ReflectionClass way is cleaner, as your method doesn't scale to more than 4 parameters. Your method will however be faster in execution time.
-
KingCrunch about 9 years@demonkoryu One may argue, that using reflection is a hack by itself, but of course you are right, that you need special methods every time the signature changes. However, this special methods are so common, that they even have a name: Factories :) On the other hand the answer is from 2011 and nowadays with variadics it's trivial to create a general purpose factory "thing", if you think it's a good idea to do so.