【问题标题】:Accessing a property in a child class which has been modified by a parent class method访问已被父类方法修改的子类中的属性
【发布时间】:2023-04-04 18:07:01
【问题描述】:

我正在开发一个应用程序,但我遇到了这个难题。下面是一个非常简化的版本,但我想知道它是否可能

例子:

class A{

    public $test = null;

    public function method1(){
      $this->test = 'finished';
    }
}

class B extends A{

    public function getMethod1Test(){
      return $this->test;
    }
}

$a = new A();
$a->method1();

$b = new B();
$b->getMethod1Test(); //this currently returns NULL

我如何修改它以使其返回值“完成”而不将修改后的值重新插入到 B 类中?

谢谢

【问题讨论】:

  • $b 是一个不同的对象。您需要在 $b->getMethod1Test() 之前调用 $b->method1()
  • 问题不在于不同的类,而在于不同的对象。每个对象都有自己的属性变量副本,除非您声明它static
  • B拨打method1()

标签: php inheritance methods parent-child


【解决方案1】:

如果你像这样创建 A 类..

class A{ 
     public $test = null; 
     public function __construct(){ // constructor
          $this->test = 'finished'; 
      }
}

虽然我还没有测试过,但应该可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-04
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多