我正在關注這篇文章,試圖讓我的每個 PHP 類都繼承自基類中定義的 getter。我會發現不用在每個班級都重寫魔法吸氣劑非常方便……(也許它有不好的后果?如果是這樣,請告訴我!)問題是我有這個錯誤:Undefined property: Personne::$nom,我不知道為什么。
這是代碼:
class classeBase {
public function __get($propriete) {
if(property_exists($this,$propriete)) return $this->$propriete;
else return null;
}
}
class Personne extends classeBase {
private $nom;
private $prenom;
//constructor...
}
$p1 = new Personne(array("nom" => "nom1", "prenom" => "prenom1"));
echo $p1->nom;
echo $p1->prenom;
3更多的精度:
- 建構式作業正常(一個
var_dump()創建的實體顯示nom1并prenom1分配良好) - 當我嘗試獲取實體的每個屬性時,我對文章的代碼有同樣的錯誤
Example_Object Personne在類中定義魔法吸氣劑時,我沒有任何錯誤
有人可以解釋一下這里發生了什么嗎?(也許我不想做的事情是不可能的)
謝謝 !
uj5u.com熱心網友回復:
問題是變數是私有的。私有變數只能從宣告它們的同一個類訪問,但您正試圖從父類訪問它們。
將它們宣告為受保護的,這允許從同一類層次結構中的任何類(無論是父類還是子類)訪問它們,但不能從這些類之外訪問它們。
<?php
class classeBase {
public function __get($propriete) {
if(property_exists($this,$propriete)) return $this->$propriete;
else return null;
}
}
class Personne extends classeBase {
protected $nom;
protected $prenom;
public function __construct($array) {
foreach ($array as $key => $value) {
$this->$key = $value;
}
}
}
$p1 = new Personne(array("nom" => "nom1", "prenom" => "prenom1"));
echo $p1->nom;
echo $p1->prenom;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/459967.html
