【问题标题】:in php why does isn't work在php中为什么不起作用
【发布时间】:2016-12-31 03:54:27
【问题描述】:
class GrandClass {
    public $data;
    public function __construct() {
        $this->someMethodInTheParentClass();
    }
    public function someMethodInTheParentClass() {
        $this->$data = 123456;
    }
}

class MyParent extends GrandClass{
    public function __construct() {
        parent::__construct();
    }
}

class Child extends MyParent {
    // public $data;
    public function __construct() {
        parent::__construct();
    }
    public function getData() {
        return $this->data; 
    }
}

$a = new Child();
var_dump($a->getData());

PHP 注意:未定义变量:D:\test.php 第 7 行中的数据

PHP 致命错误:无法在第 7 行访问 D:\test.php 中的空属性

【问题讨论】:

  • 使用 $this->data 而不是 $this->$data
  • $this->data 而不是 $this->$data
  • $this->$data = 123456;更改为 $this->data = 123456;
  • 전창한 检查 cmets 和答案,并将其中一个标记为接受。谢谢

标签: php class extends


【解决方案1】:

MyParent 和 Child 类中的构造函数是不必要的。

【讨论】:

    【解决方案2】:
    Use  `$this->data = 123456; `instead of`  $this->$data = 123456;` in below function
    
    public function someMethodInTheParentClass() {
            $this->data = 123456;
    }
    

    【讨论】:

    • 如果可以的话,你可能想充实你的答案,也许你的答案有点格式:)
    【解决方案3】:

    使用 $this->data = 123456; 更新您的函数 someMethodInTheParentClass;

     public function someMethodInTheParentClass() {
            $this->data = 123456;
        }
    

    【讨论】:

      猜你喜欢
      • 2013-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      • 2013-09-02
      相关资源
      最近更新 更多