![](/img/trans.png)
[英]property_exists() to check if static property exists inside class method
[英]PHP : call property_exists() function inside of the Abstract method called from within the Child class
我想在Abstract類中創建setProperties()方法,如下所示:
public function setProperties($array = null) {
if (!empty($array)) {
foreach($array as $key => $value) {
if (property_exists($this, $key)) {
$this->{$key} = $value;
}
}
}
}
我不太確定的是,我是否能夠在繼承自此Abstract類的類中使用它來設置繼承的屬性以及特定的子類。
我不確定我是否應該在property_exists()函數中使用任何其他關鍵字然后使用$ this - 也許有一種方法可以使用后期靜態綁定(static::)關鍵字?
$this
是特定於實例的,因此, property_exists
將與子類一起正常工作。
你的代碼基本上應該工作。 想象一下這個簡單的例子,輸出兩次是true
:
abstract class A {
protected $var1;
public function exists1() {
var_dump(property_exists($this, 'var2'));
}
}
class B extends A {
protected $var2;
public function exists2() {
var_dump(property_exists($this, 'var1'));
}
}
$o = new B();
$o->exists1();
$o->exists2();
如您所見,當父類正在嘗試訪問子成員時, property_exists()
在子類從父類訪問成員時起作用,反之亦然。
這是抽象的基本概念之一。 你要做的事情絕對可以。 如果你得到一個錯誤,它必須是一個有點監督的細節
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.