由於此修正 https://bugs.php.net/bug.php?id=49719,hasProperty() 現在與 getProperty() 和 getProperties() 方法一致。
hasProperty() 不再針對父類別的私有屬性返回 true。
(PHP 5 >= 5.1.2, PHP 7, PHP 8)
ReflectionClass::hasProperty — 檢查屬性是否已定義
name
要檢查的屬性名稱。
範例 #1 ReflectionClass::hasProperty() 範例
<?php
class Foo {
public $p1;
protected $p2;
private $p3;
}
$obj = new ReflectionObject(new Foo());
var_dump($obj->hasProperty("p1"));
var_dump($obj->hasProperty("p2"));
var_dump($obj->hasProperty("p3"));
var_dump($obj->hasProperty("p4"));
?>
上述範例將輸出類似以下的內容
bool(true) bool(true) bool(true) bool(false)
由於此修正 https://bugs.php.net/bug.php?id=49719,hasProperty() 現在與 getProperty() 和 getProperties() 方法一致。
hasProperty() 不再針對父類別的私有屬性返回 true。
由於此修正 https://bugs.php.net/bug.php?id=49719,hasProperty() 現在與 getProperty() 和 getProperties() 方法一致。
hasProperty() 不再針對私有屬性返回 true。
請注意,此方法不保證您可以使用 ReflectionClass::getProperty() 取得屬性。
ReflectionClass::hasProperty() 會考慮父類別(但忽略私有屬性不會被繼承),而 ReflectionClass::getProperty() 和 ReflectionClass::getProperties() 不會考慮繼承。
(使用 PHP 5.3.0 測試)
<?php
類別 Foo
{
私有 $x;
}
類別 Bar 延伸 Foo
{
//
}
$foo = new ReflectionClass('Foo');
$bar = new ReflectionClass('Bar');
var_dump($foo->hasProperty('x')); // bool(true)
var_dump($bar->hasProperty('x')); // bool(true)
var_dump(get_class($foo->getProperty('x'))); //string(18) "ReflectionProperty"
try {
$bar->getProperty('x');
} catch (ReflectionException $e) {
echo $e->getMessage(); // 屬性 x 不存在
}
?>