使用父对象作为参数调用php子类构造函数



我对php语法还不太好,所以我的问题是:

我有一个班Foo。

Class Bar扩展Foo。

我想为Bar创建一个构造函数,该构造函数以Foo类的实例作为参数进行调用,并创建一个看起来与Foo类实例相似的Bar实例。

我似乎不得不这么做,因为Foo是WordPress插件中的一个类。我正在写一个插件,在原始插件的基础上,在我可以添加的过滤器中,我得到了Foo对象。

我愿意以"正确"的方式做这件事,如果我能学会"正确"方式的话。

所以:

class Foo {      // in the original plugin
   public function __construct() {
       <do some stuff>
   }
}
class Bar extends Foo {     // in my plugin to extend the original plugin
   public function __construct($myFooObject) {
      <I want: $this = $myFooObject; but it doesnt work>
      <do some stuff special to Bar>
   }
}

好吧。您已经继承了Foo类的特性和成员。您只是错过了调用父类的构造函数(Foo的构造函数)。

在酒吧的__construct():中添加以下行

parent::__constrcut();

条现在看起来是这样的:

class Bar extends Foo {     // in my plugin to extend the original plugin
   public function __construct($myFooObject) {
      parent::__construct(); // we've added this line to call the parent constructor
      <do some stuff special to Bar>
   }
}

在子类构造函数中调用父构造函数可以保持对象的完整性,还允许子类动态访问其父类。

<?php
class Bar extends Foo { // in my plugin to extend the original plugin
   public function __construct($myFooObject) {
     foreach (get_object_vars($myFooObject) as $key=>$value){
        $this->$key = $value;
     }
     // <I want: $this = $myFooObject; but it doesnt work>
     // <do some stuff special to Bar>
   }
}

这不仅会使用Foo属性进行实例化,还会在创建时复制$myFooObject属性。

最新更新