PHP:如何使用另一个类中的参数实例化一个类

标签 php oop class object instantiation

我处于这样一种情况,我需要用另一个类的实例中的参数实例化一个类。 这是原型(prototype):

//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/en/class.reflectionclass.php

if(count($args) == 0)
   $obj = new $className;
else {
   $r = new ReflectionClass($className);
   $obj = $r->newInstanceArgs($args);
}

关于PHP:如何使用另一个类中的参数实例化一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1858254/

相关文章:

phpize 报告 "Cannot find config.m4"

javascript - 在javascript中将值设置为__proto_ _` and `原型(prototype)

c++ - 错误 : expected primary-expression before & token

PHP对象嵌套问题

php - 使用 php 连接到 mysql 数据库

php - "require_once(): Failed opening required"但文件存在并且可读

javascript - 尝试用一些代码扩展 HTMLInputElement 原型(prototype)

java - Java 中的多态性与服务

java - 从类中调用方法错误

c++ - 尝试学习类(class)和 'heap' c++