【问题标题】:How do I access a modified parent variable within child classes in PHP如何在 PHP 的子类中访问修改后的父变量
【发布时间】:2015-04-15 10:27:52
【问题描述】:

从 php 中的扩展类访问动态父变量的最佳方法是什么?

在下面的示例中,我基本上简化了我想要做的事情。我需要能够从子类访问变量 '$variable'。但是,$variable 在构造 A 类时会发生变化,但对 B 类和 C 类的定义不会改变。

 class A {

 protected $variable = 'foo';
  public function __construct(){
    $this->variable = 'bar';
    echo($this->variable);
    $B = new B();                   //Returns 'bar'
  }
 }

 class B extends A {
   public function __construct(){
     echo($this->variable);         //Returns 'foo'
     $C = new C();
   }
 }

 class C extends B {
   public function __construct() {
     echo($this->variable);         //Returns 'foo'
   }
 }

 $A = new A();

我基本上需要 $this->variable 来为所有扩展类返回 bar。经过研究,最推荐的解决方案是为子 __construct 中的每个类调用 __construct 方法,但这在这种情况下不起作用,因为正在调用子类来自父类。

有人可以帮忙吗?谢谢:)

【问题讨论】:

  • 您应该在派生类构造函数中调用parent::__construct。这将调用父构造函数并将$this->variable 设置为bar

标签: php class variables dynamic


【解决方案1】:

让子类继承父类的构造函数集变量的唯一方法是调用父类的构造函数。

也许这就是答案?

class A {
 protected $variable = 'foo';
  public function __construct(){
    $this->variable = 'bar';
    echo($this->variable);
  }
  public function init(){
    $B = new B();
    //Carry on
    $B->init();
  }
 }

 class B extends A {
   public function __construct(){
     parent::__construct();
     echo($this->variable);
   }
   public function init(){
     $C = new C();
     //Carry on
   }
 }

 class C extends B {
   public function __construct() {
     parent::__construct();
     echo($this->variable);
   }
 }

 $A = new A();
 $A->init();

有两个函数调用很麻烦。也许不同的设计模式是要走的路?

【讨论】:

  • 您不能使用点语法来访问 PHP 中的方法...我猜您来自 Java 或其他语言?应该是$B->init()$A->init()
  • 谢谢!你说得对,我大部分时间都是 C++ 程序员,当我看到这个时,我正在编写一些代码。
【解决方案2】:

正如@theoemms 所指出的,除非您使用parent::__construct() 显式调用它,否则不会调用父构造函数。另一种解决方法是使用get_called_class()(自 PHP 5.3 起可用)检查正在实例化的类:

class A {

 protected $variable = 'foo';
  public function __construct(){
    $this->variable = 'bar';
    echo($this->variable);
    if (get_called_class() == 'A') {
      $B = new B();                   //Returns 'bar'
    }
  }
 }

 class B extends A {
   public function __construct(){
     parent::__construct();
     echo($this->variable);         //Returns 'bar'
     if (get_called_class() == 'B') {
       $C = new C();
     }
   }
 }

 class C extends B {
   public function __construct() {
     parent::__construct();
     echo($this->variable);         //Returns 'bar'
   }
 }

 $A = new A();

但我想知道,您为什么需要这样做?如果您遇到这种情况,我认为您的课程可能存在设计缺陷......

【讨论】:

  • 感谢您的回复。您的解决方案也有效,但@theoemms 更适合我的情况。此外,这并不是设计缺陷......我只是在尝试链接类:)
猜你喜欢
  • 2016-06-02
  • 2018-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-21
相关资源
最近更新 更多