脚本宝典收集整理的这篇文章主要介绍了PHP:如何使用另一个类中的参数实例化一个类,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
//test.PHP class test { function __construct($a,$b,$c) { echo $a . '<br />'; echo $b . '<br />'; echo $c . '<br />'; } }
现在,我需要使用下面的类cls函数来实例化上面的类:
class myclass { function cls($file_name,$args = array()) { include $file_name . ".PHP"; if (isset($args)) { // this is where the PRoblem might be,i need to pass as many arguments as test class has. $class_instance = new $file_name($args); } else { $class_instance = new $file_name(); } return $class_instance; } }
现在,当我尝试创建测试类的实例,同时传递参数:
$myclass = new myclass; $test = $myclass->cls('test',array('a1','b2','c3'));
如果我实例化一个在它的构造函数中没有参数的类,这个工作正常.
对于经验丰富的PHP开发人员来说,以上不应该是很大的问题.请帮忙.
谢谢
if(count($args) == 0) $obj = new $classname; else { $r = new ReflectionClass($className); $obj = $r->newInstanceArgs($args); }
以上是脚本宝典为你收集整理的PHP:如何使用另一个类中的参数实例化一个类全部内容,希望文章能够帮你解决PHP:如何使用另一个类中的参数实例化一个类所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。