PHP:如何使用另一个类中的参数实例化一个类 [英] PHP: How to instantiate a class with arguments from within another class
问题描述
我处于一种需要用另一个类的实例中的参数实例化一个类的情况. 这是原型:
I am in a situations where i need to instantiate a class with arguments from within an instance of another class. Here is the prototype:
//test.php
class test
{
function __construct($a, $b, $c)
{
echo $a . '<br />';
echo $b . '<br />';
echo $c . '<br />';
}
}
现在,我需要使用下面的类的 cls 函数实例化上面的类:
Now, i need to instantiate above class using below class's cls function:
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;
}
}
现在,当我尝试向其传递参数时尝试创建测试类的实例时:
Now when i try to create an instance of test class while passing arguments to it:
$myclass = new myclass;
$test = $myclass->cls('test', array('a1', 'b2', 'c3'));
它给出了错误: 缺少论点1和2;仅传递第一个参数.
It gives error: Missing argument 1 and 2; only first argument is passed.
如果我实例化一个在其构造函数中没有任何参数的类,这将很好地工作.
This works fine if i instantiate a class which has no arguments in it's constructor function.
对于有经验的PHP开发人员而言,上述问题不应该太大.请帮忙.
For experienced PHP developers, above should not be much of a problem. Please help.
谢谢
推荐答案
您需要反射 http ://php.net/manual/en/class.reflectionclass.php
if(count($args) == 0)
$obj = new $className;
else {
$r = new ReflectionClass($className);
$obj = $r->newInstanceArgs($args);
}
这篇关于PHP:如何使用另一个类中的参数实例化一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!