PHP faked multiple inheritance - having object attributes set in fake parent class available in extended class

可紊 提交于 2019-12-10 10:38:18

问题


I have used faking of multiple inheritance as given in Can I extend a class using more than 1 class in PHP?

Notice that class A actually extends class B and faking is done for extending from class C.

It was working fine until I needed an attribute set in a function of class C to be available in class A. Consider a little edited version of that code where I call a function of class C from inside a function of class A :-

//Class A
class A extends B
{
  private $c;

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

  // fake "extends C" using magic function
  public function __call($method, $args)
  {
    return call_user_func_array(array($this->c, $method), $args);
  }

//calling a function of class C from inside a function of class A
  public function method_from_a($s) {
     $this->method_from_c($s);
     echo $this->param; //Does not work
  }

//calling a function of class B from inside a function of class A
  public function another_method_from_a($s) {
     $this->method_from_b($s);
     echo $this->another_param; //Works
  }
}

//Class C

class C {
    public function method_from_c($s) {
        $this->param = "test";
    }
}

//Class B
class B {
    public function method_from_b($s) {
        $this->another_param = "test";
    }
}


$a = new A;
$a->method_from_a("def");
$a->another_method_from_a("def");

So, an attribute set in a function of class C is not available afterwards in class A but if set in class B, it is available in class A. What adjustment am I missing so as to make setting of attributes in the fake parent class work like real? An attribute set in fake parent's function should be available in all the classes of the hierarchy like in normal case.

Thanks

Solved
I added the magic function __get() in class A and it worked.

public function __get($name)
{   
   return $this->c->$name;
}

回答1:


That will never work, because 'param' is not a property of A: it is in c, which is a property of A.

What you need to do is define the magic methods such as __set and __get, which parallel __call for properties.



来源:https://stackoverflow.com/questions/4143722/php-faked-multiple-inheritance-having-object-attributes-set-in-fake-parent-cla

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!