【问题标题】:PHP - Faked Multiple inheritance - How to pass multiple parameters to functionsPHP - 伪造的多重继承 - 如何将多个参数传递给函数
【发布时间】:2011-04-12 16:20:24
【问题描述】:

我在搜索如何在 PHP 中伪造多重继承时发现了这一点(因为 PHP 不直接支持多重继承)。

Can I extend a class using more than 1 class in PHP?

这是那里给出的完整代码:-

class B {
    public function method_from_b($s) {
        echo $s;
    }
}

class C {
    public function method_from_c($s) {
        echo $s;
    }
}

class A extends B
{
  private $c;

  public function __construct()
  {
    $this->c = new C;
  }

  // fake "extends C" using magic function
  public function __call($method, $args)
  {
    $this->c->$method($args[0]);
  }
}


$a = new A;
$a->method_from_b("abc");
$a->method_from_c("def");

问题
此处给出的示例仅考虑函数C::method_from_c($s) 的一个参数。它适用于一个参数,但我有几个class C 的函数,有些有 2 个,有些有 3 个参数,如下所示:-

class C {
    public function method_from_c($one,$two) {
        return $someValue;
    }

    public function another_method_from_c($one,$two, $three) {
        return $someValue;
    }
}

而且我不想更改 C 类的函数定义中的任何内容(它必须接受那么多参数)。例如。我不想像这样在C::method_from_c($s,$two) 中使用 func_get_args():-

public function method_from_c() 
{

     $args = func_get_args();

     //extract params from $args and then treat each parameter
}

class A__call() 函数内部做什么才能使其工作。我希望能够调用Class C 之类的函数$obj->method_from_c($one,$two);

谢谢
桑迪潘

【问题讨论】:

    标签: php parameter-passing multiple-inheritance


    【解决方案1】:

    你可以使用call_user_func_array:

    function __call($method, $args) {
        call_user_func_array(array(&$this->c, $method), $args);
    }
    

    请注意,这不会表现得那么好。

    【讨论】:

    • $this->c 的引用运算符是多余的
    • @sandeepan:实际上我不确定,但我隐约记得在某处读到 $foo->$bar() 比使用 call_user_func 执行得更好。
    【解决方案2】:

    您可以在manual这里找到答案?

    public function __call($method_name, $args)
    {
       return call_user_method_array($method_name, $this->c, $args);
    }
    

    【讨论】:

    • Raoul Duke 的回答比我的好——(不推荐使用 call_user_method fns)
    猜你喜欢
    • 2016-04-25
    • 2021-07-02
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    相关资源
    最近更新 更多