PHP在创建新对象(对象的call_user_func_array)时传递参数 [英] PHP passing parameters while creating new object, call_user_func_array for objects
本文介绍了PHP在创建新对象(对象的call_user_func_array)时传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想动态创建一个PHP对象,并且参数是可选的.
I would like to dynamically create a PHP object, and parameters would be optional.
例如,不要这样做:
$test = new Obj($param);
我想做这样的事情(创建新的ob是虚构的):
I would like to do something like this (create new ob is fictional):
$test = create_new_obj('Obj', $param);
php中是否有这样的功能?类似于call_user_func_array,但针对对象.
Is there such function in php? Something similar to call_user_func_array, but for object instead.
推荐答案
从PHP 5.6开始,您现在可以使用新的Argument Unpacking运算符(...)用单行代码来实现.
As of PHP 5.6, you can now achieve this with a single line of code by using the new Argument Unpacking operator (...).
这是一个简单的例子.
$className='Foo';
$args=['arg1','arg2','arg3'];
$newClassInstance=new $className(...$args);
请参见 PHP变长参数列表了解更多信息.
这篇关于PHP在创建新对象(对象的call_user_func_array)时传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文