PHP Conference Nagoya 2025

ReflectionClass::hasProperty

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

ReflectionClass::hasProperty检查属性是否已定义

说明

public ReflectionClass::hasProperty(string $name): bool

检查指定的属性是否已定义。

参数

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 notes

up
0
dalguete at gmail dot com
3 years ago
hasProperty() now is consistent with getProperty() and getProperties() methods, thanks to this fix https://bugs.php.net/bug.php?id=49719

hasProperty() no longer returns true in private properties from parent classes.
up
-1
dalguete at gmail dot com
3 years ago
hasProperty() now is consistent with getProperty() and getProperties() methods, thanks to this fix https://bugs.php.net/bug.php?id=49719

hasProperty() no longer returns true in private properties.
up
-2
rwilczek at web-appz dot de
15 years ago
Note, that this method does not guarantee, that you can get a property with ReflectionClass::getProperty().

ReflectionClass::hasProperty() considers the parent classes (ignoring however, that a private property is not inherited), while ReflectionClass::getProperty() and ReflectionClass::getProperties() don't care about inheritance.

(Tested with PHP 5.3.0)

<?php
class Foo
{
private
$x;
}

class
Bar extends 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(); // Property x does not exist
}
?>
To Top