2012-03-06 51 views
1

我正在嘗試學習OOP並有幾個問題。我已閱讀了PHP Objects, Patterns, and Practice的前幾章,以及以下帖子; Nettuts+PHP FreaksPHPRONoob PHP OOP問題:構造函數和捲曲支架

  1. 在子類中,構造函數是否必須列出已經存在於父類中的變量?
  2. 當我在我的方法(或其他地方)中檢索一個屬性時,爲什麼我需要將我的值包裹在大括號中(即{$ this-> id})?另外,如果有人有任何建議(例如我做錯了什麼),我可以接受任何批評。

class Element { 
    public $tag; 
    public $id; 

    function __construct($tag, $id) { 
    $this->tag = $tag; 
    $this->id = $id; 
    } 

    public function getAttributes() { 
    return "id='{$this->id}'"; 
    } 
} 


class NormalElement extends Element { 
    public $text; 

    function __construct($tag, $id, $text) { 
    parent::__construct($tag, $id); 
    $this->text = $text; 
    } 

    public function getElement() { 
    return "<{$this->tag}>{$this->text}</{$this->tag}>"; 
    } 
} 

class VoidElement extends Element { 

    function __construct($tag, $id) { 
    parent::__construct($tag, $id); 
    } 

    public function getElement() { 
    return "<{$this->tag} " . parent::getAttributes() . " />"; 
    } 
} 

我花了一段時間試圖讓我的代碼,在這篇文章中正確顯示,但它不斷地刷新。

+2

哇......那是有史以來最詭異的經歷,試圖鱈魚在SO上格式化一個帖子...有關該有序列表的東西......必須拋出規則才能使其運行。 – prodigitalson 2012-03-06 05:34:08

回答

3
  1. 不可以。您可以調用父類的構造函數。但是,如果需要將此值作爲參數,則需要爲子類的構造函數提供額外參數
  2. 當您在字符串中編寫值並使用->運算符時,需要將其包裝在大括號中,以便PHP知道你在說的是一個成員,而不是$this本身。
2

2)因爲PHP解析停止嵌入引用的字符串變量,當它到達一個字符變量名中使用無效的(在這種情況下,「 - 」)。然後它假設 - 只是字符串文字的一部分。當然,除非你用花括號包裹它。