Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP passing parameters while creating new object, call_user_func_array for objects

Tags:

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.

like image 654
Patrick Avatar asked Mar 31 '10 03:03

Patrick


People also ask

Are objects passed by value or by reference PHP?

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.

What is parameter passing in PHP?

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.

How do I declare an object in PHP?

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.

What is call user func in PHP?

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 $... ]])


1 Answers

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.

like image 134
TimChandler Avatar answered Oct 26 '22 22:10

TimChandler