简体   繁体   English

动态实例化另一个类

[英]Dynamically instantiate class from another

I made an example to better explain the situation. 我举了一个例子来更好地解释这种情况。 If I run this 如果我运行这个

class A
{
    public function __construct()
    {
        return new B(func_get_args());
    }
}

class B
{
    public function __construct()
    {
        var_dump(func_get_args());
    }
}

$obj = new A('a', 'b', 'c');

I get 我懂了

array(1) {
  [0]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}

But what if the constructor prototype of B is public function __construct($var1, $va2, $var3) ? 但是,如果B的构造函数原型是public function __construct($var1, $va2, $var3)呢? How could I pass the parameters to it if I don't know the exact numbers of parameters of the B constructor? 如果我不知道B构造函数的确切参数数量,该如何将参数传递给它?

This may not be the one which you are looking for, But with the best of my knowledge I think there is no other solution. 这可能不是您要找的那种,但是据我所知,我认为没有其他解决方案。

Class A {
        public function __construct()
        {
            return new B(func_get_args());
        }
    }

    class B
    {
        public function __construct($paramArr = array())
        {
            var_dump($paramArr);
        }
    }

    $obj = new A('a', 'b', 'c');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM