PHP - 获取类公共变量? [英] PHP - Get Classes public variables?
本文介绍了PHP - 获取类公共变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑下面的代码.
class A {
public function __construct() {
}
}
class B extends A {
public $a = "a";
public $b = "b";
public $c = "c";
}
如何在不确切知道它们是什么的情况下从父类中获取 B 类的公共变量?
How do I get the class B's public variables from within the parent class without knowing precisely what they are?
推荐答案
class A {
public $d;
public function __construct() {
$reflect = new ReflectionClass($this);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
var_dump($props);
}
}
class B extends A {
public $a = "a";
private $b = "b";
public $c = "c";
}
new B();
输出(注意没有'b',但A的公共'd'在那里,并提到它在A中声明):
Output (notice no 'b', but A's public 'd' is in there, with a mention it's declared in A):
array(3) {
[0]=>
&object(ReflectionProperty)#3 (2) {
["name"]=>
string(1) "a"
["class"]=>
string(1) "B"
}
[1]=>
&object(ReflectionProperty)#4 (2) {
["name"]=>
string(1) "c"
["class"]=>
string(1) "B"
}
[2]=>
&object(ReflectionProperty)#5 (2) {
["name"]=>
string(1) "d"
["class"]=>
string(1) "A"
}
}
这篇关于PHP - 获取类公共变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文