开发者

PHP - Faked Multiple inheritance - How to pass multiple parameters to functions

I found this while searching for how to fake multiple inheritance in PHP (since PHP does not support multiple inheritance directly).

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

Here is the complete code given there:-

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");

The problem

The example given here considers only one parameter for the function C::method_from_c($s). It works fine with one parameter but I have several functions of class C, some having 2, some having 3 parameters like this:-

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

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

And I do not want to change anything in Class C's function definition (It must accept those many parameters). E.g. I do not want to use func_get_args() inside my C::method_from_c($s,$two) like this:-

public function method_from_c() 
{

     $arg开发者_如何学运维s = func_get_args();

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

What to do inside the __call() function of class A so that it works. I want to be able to call Class C functions like $obj->method_from_c($one,$two);

Thanks

Sandeepan


you can use call_user_func_array:

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

note that this won't perform as well though.


You can find the answer here in the manual?

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜