PHP伪造了多重继承-在扩展类中提供了在伪父类中设置的对象属性 [英] PHP faked multiple inheritance - having object attributes set in fake parent class available in extended class

查看:100
本文介绍了PHP伪造了多重继承-在扩展类中提供了在伪父类中设置的对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了请注意,A类实际上是对B类的扩展,伪造是为了对C类进行扩展.

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

在我需要在C类的函数中设置一个属性集才能在A类中使用之前,它工作正常.考虑一下该代码的一些经过编辑的版本,在该版本中,我从A类的函数内部调用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");

因此,在类C的函数中设置的属性此后在类A中不可用,但是如果在类B中设置,则在类A中可用.家长班的工作像真实的吗?像在正常情况下一样,在假父代函数中设置的属性应该在层次结构的所有类中都可用.

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.

谢谢

已解决
我在A类中添加了魔术函数__get(),它起作用了.

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

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

推荐答案

这将永远无法工作,因为'param'不是A的属性:它在c中,而c是A的属性.

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

您需要做的是定义魔术方法例如__set和__get,它们与__call属性并行.

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

这篇关于PHP伪造了多重继承-在扩展类中提供了在伪父类中设置的对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆