修改另一个类的PHP类属性?

时间:2016-02-04 06:38:51

标签: class properties

我的代码:

class A{

   function __construct(){
      $foo1 = new Foo1();
      $foo2 = new Foo2();
      $this->copy_property($foo1);           
      $this->copy_property($foo2);           
   }

   private function copy_property($obj){
      foreach (get_object_vars($obj) as $k => $v) $this->$k = $v;
   }
}

$bar = new A();

现在我的对象$ bar包含来自对象$ foo1和$ foo2的所有属性 但是我怎样才能使用方法" copy_property"对于另一个类(B,C,D ......)而没有重新定义它?

例如:

class B{
   function __construct(){
      $foo3 = new Foo3();
      $foo4 = new Foo4();
      $this->copy_property($foo3);           
      $this->copy_property($foo4); 
   }

   // I must redefine this method here, and class C,D,E...
   private function copy_property($obj){
      foreach (get_object_vars($obj) as $k => $v) $this->$k = $v;
   }
}
$bar2 = new B();

P / s:出于某些原因,我想在A类中创建对象foo1,foo2

1 个答案:

答案 0 :(得分:0)

首先,private将不允许您从其他类访问该方法,然后将该函数从normal转换为static或使用依赖注入设计模式来实现您的目标。

请将访问修饰符更改为公开

      class A{

       function __construct(){
          $foo1 = new Foo1();
          $foo2 = new Foo2();
          $this->copy_property($foo1);           
          $this->copy_property($foo2);           
       }

        function copy_property($obj){//function access modifier changed
          foreach (get_object_vars($obj) as $k => $v) $this->$k = $v;
       }
    }

    $bar = new A();


        class B{
$aObj;
       function __construct($obj){
         $this->aObj=$obj;
         // now you can run function of class A as
          $this->aObj->copy_property();
       }


    }
    $bar2 = new B($bar);//injecting object of class A from outside