PHP 8.5.8 Released!

ReflectionClass::getDefaultProperties

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getDefaultProperties获取默认属性

说明

public function ReflectionClass::getDefaultProperties(): array

获取类的默认属性(包括了继承的属性)。

注意:

当在内部类中使用时,此方法仅用于静态属性,当在用户定义类中使用此方法时,无法追踪静态类属性的默认值。

参数

此函数没有参数。

返回值

默认属性的 array ,其键是属性的名称,其值是属性的默认值或者 null (如果没有默认值)。这个函数不区分静态和非静态属性,也不考虑可见性修饰符。

示例

示例 #1 ReflectionClass::getDefaultProperties() 示例

<?php
class Bar {
 protected $inheritedProperty = 'inheritedDefault';
}
class Foo extends Bar {
 public $property = 'propertyDefault';
 private $privateProperty = 'privatePropertyDefault';
 public static $staticProperty = 'staticProperty';
 public $defaultlessProperty;
}
$reflectionClass = new ReflectionClass('Foo');
var_dump($reflectionClass->getDefaultProperties());
?>

以上示例会输出:

array(5) {
 ["staticProperty"]=>
 string(14) "staticProperty"
 ["property"]=>
 string(15) "propertyDefault"
 ["privateProperty"]=>
 string(22) "privatePropertyDefault"
 ["defaultlessProperty"]=>
 NULL
 ["inheritedProperty"]=>
 string(16) "inheritedDefault"
}

参见

发现了问题?

了解如何改进此页面提交拉取请求报告一个错误
+添加备注

用户贡献的备注 2 notes

up
4
articice at ua dot fm
10 years ago
runaurufu is not quite right, get_class_vars() does not return protected params, while this one does.
Thus it's extremely useful when having an abstract parent class and protected properties overriding in children.
For example, I use a class factory and one of the children has some static test methods that still need to output a paramether name, like $this->name, etc. With this example code, one can use static::getNotStaticProperty('name'), but not get_class_vars('name').
Try it:
trait static_reflector {
 /*
 * a purely static function that returns default properties of the non-static instance of the same class
 */
 static protected function getNonStaticProperty($key) {
 $me = get_class();
 $reflectionClass = new \ReflectionClass($me);
 $properties_list = $reflectionClass->getDefaultProperties();
 if (isset($properties_list[$key]))
 return $var_name = $properties_list[$key];
 else throw new RuntimeException("BUG: Unable to reflect non-static property '{$key}' from default properties of class {$me}");
 }
}
class a {
 use \static_reflector;
 protected $key_a = 'test ok';
 public static function test() {
 echo static::getNonStaticProperty('key_a')."\n";
 try {
 print static::getNonStaticProperty('key_b');
 echo "FAIL No exception thrown";
 } catch (RuntimeException $e) {
 echo "OK ".$e->getMessage();
 }
 }
}
echo get_class_vars('a')['key_a']; 
a::test();
this will return:
Notice: Undefined index: key_a in ...
test ok
OK BUG: Unable to reflect non-static property 'key_b' from default properties of class a
ps: Yes, this is copied from a unit test.
up
2
runaurufu AT gmail.com
14 years ago
Worth noting that it will not return private parameters of parent class...
so it works exactly as get_class_vars or get_object_vars
+添加备注

AltStyle によって変換されたページ (->オリジナル) /