PHP Conference Japan 2024

ReflectionClass::hasProperty

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

ReflectionClass::hasProperty檢查屬性是否已定義

說明

public ReflectionClass::hasProperty(字串 $name): 布林值

檢查指定的屬性是否已定義。

參數

name

要檢查的屬性名稱。

返回值

如果具有該屬性,則返回 true,否則返回 false

範例

範例 #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)

參見

新增註釋

使用者貢獻的註釋 3 則註釋

dalguete at gmail dot com
3 年前
由於此修正 https://bugs.php.net/bug.php?id=49719,hasProperty() 現在與 getProperty() 和 getProperties() 方法一致。

hasProperty() 不再針對父類別的私有屬性返回 true。
dalguete at gmail dot com
3 年前
由於此修正 https://bugs.php.net/bug.php?id=49719,hasProperty() 現在與 getProperty() 和 getProperties() 方法一致。

hasProperty() 不再針對私有屬性返回 true。
rwilczek at web-appz dot de
15 年前
請注意,此方法不保證您可以使用 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 不存在
}
?>
To Top