[英]PHP: How to instantiate a class with arguments from within another class
我处在需要使用另一个类实例中的参数实例化一个类的情况下。 这是原型:
//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'));
它给出错误:缺少参数1和2; 仅传递第一个参数。
如果我实例化在其构造函数中没有参数的类,则此方法很好。
对于经验丰富的PHP开发人员来说,上述问题不应该太大。 请帮忙。
谢谢
您需要反射http://php.net/manual/zh/class.reflectionclass.php
if(count($args) == 0)
$obj = new $className;
else {
$r = new ReflectionClass($className);
$obj = $r->newInstanceArgs($args);
}
您可以:
1)修改测试类以接受包含您要传递的数据的数组。
//test.php
class test
{
function __construct($a)
{
echo $a[0] . '<br />';
echo $a[1] . '<br />';
echo $a[2] . '<br />';
}
}
2)使用用户方法而不是构造函数进行初始化,然后使用call_user_func_array()
函数对其进行调用。
//test.php
class test
{
function __construct()
{
}
public function init($a, $b, $c){
echo $a . '<br />';
echo $b . '<br />';
echo $c . '<br />';
}
}
在您的主班:
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);
call_user_func_array(array($class_instance,'init'), $args);
}
else
{
$class_instance = new $file_name();
}
return $class_instance;
}
}
http://www.php.net/manual/zh/function.call-user-func-array.php
最后,您可以将构造函数参数留空,并使用func_get_args()
。
//test.php
class test
{
function __construct()
{
$a = func_get_args();
echo $a[0] . '<br />';
echo $a[1] . '<br />';
echo $a[2] . '<br />';
}
}
class textProperty
{
public $start;
public $end;
function textProperty($start, $end)
{
$this->start = $start;
$this->end = $end;
}
}
$ object = new textProperty($ start,$ end);
不工作吗
我找到的最简单的方法是:
if ($depCount === 0) {
$instance = new $clazz();
} elseif ($depCount === 1) {
$instance = new $clazz($depInstances[0]);
} elseif ($depCount === 2) {
$instance = new $clazz($depInstances[0], $depInstances[1]);
} elseif ($depCount === 3) {
$instance = new $clazz($depInstances[0], $depInstances[1], $depInstances[2]);
}
不好意思,但是您应该了解这个想法。
我们现在是2019年,现在有了php7 ...并且我们拥有spread-operator(...)。 现在我们可以简单地致电
<?php
class myclass
{
function cls($file_name, $args = array())
{
include $file_name . ".php";
if (isset($args))
{
$class_instance = new $file_name(...$args); // <-- notice the spread operator
}
else
{
$class_instance = new $file_name();
}
return $class_instance;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.