I would like to dynamically create a PHP object, and parameters would be optional.
For example, instead of doing this:
$test = new Obj($param);
I would like to do something like this (create new ob is fictional):
$test = create_new_obj('Obj', $param);
Is there such function in php? Something similar to call_user_func_array, but for object instead.
Introduction. In PHP, objects are passed by references by default. Here, reference is an alias, which allows two different variables to write to the same value. An object variable doesn't contain the object itself as value.
Introduction. In PHP, arguments to a function can be passed by value or passed by reference. By default, values of actual arguments are passed by value to formal arguments which become local variables inside the function. Hence, modification to these variables doesn't change value of actual argument variable.
To create an Object in PHP, use the new operator to instantiate a class. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.
The call_user_func() is an inbuilt function in PHP which is used to call the callback given by the first parameter and passes the remaining parameters as argument. It is used to call the user-defined functions. Syntax: mixed call_user_func ( $function_name[, mixed $value1[, mixed $... ]])
As of PHP 5.6, you can now achieve this with a single line of code by using the new Argument Unpacking operator (...).
Here is a simple example.
$className='Foo'; $args=['arg1','arg2','arg3']; $newClassInstance=new $className(...$args);
See PHP Variable-length argument lists for more information.
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