代码之家  ›  专栏  ›  技术社区  ›  Sandeepan Nath

PHP伪造了多重继承-在扩展类中的假父类中设置了对象属性

  •  2
  • Sandeepan Nath  · 技术社区  · 15 年前

    我用了伪造的多重继承 Can I extend a class using more than 1 class in PHP?

    注意,类A实际上扩展了类B,而伪造是为了从类C扩展而完成的。

    在我需要在类C的函数中设置一个属性以便在类a中可用之前,一切都很顺利。请考虑该代码的一个小编辑版本,在该版本中,我从类a的函数中调用类C的函数:-

    //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中可用。我缺少什么调整,以使假父类中的属性设置像真的一样工作?在伪父函数中设置的属性应该在层次结构的所有类中都可用,就像在正常情况下一样。

    谢谢

    解决了的

    public function __get($name)
    {   
       return $this->c->$name;
    }
    
    1 回复  |  直到 9 年前
        1
  •  2
  •   Colin Fine    15 年前

    这永远行不通,因为“param”不是a的属性:它在c中,这是a的属性。

    magic methods 例如“set”和“get”,它们并行地调用属性。