簡體   English   中英

PHP對象繼承:如何訪問父屬性?

[英]PHP object inheritance : how to access parent attributes?

我為PHP對象繼承編寫了這個小測試腳本:

<?php

class A {
    protected $attr;

    public function __construct($attr) {
        $this->$attr = $attr;
    }

    public function getAttr() {
        return $this->attr;
    }
}

class B extends A {

}

$b = new B(5);
echo $b->getAttr();

這什么也不顯示! 為什么不顯示5 B級不是應該像A級嗎?

錯誤在這里:

$this->$attr = $attr;

您在此處分配$attr $this->{5}$attr的值)。

寫,以解決該屬性:

$this->attr = $attr;
//     ^------ please note the removed `$` sign

要注意到在這種情況下發生了什么,請嘗試轉儲對象: var_dump($b);

您正在使用變量變量,而不是直接訪問變量

 $this->$attr = $attr;
        ^
        |----- Remove This

 $this->attr = $attr;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM