直接帖代码
使用ReflectionClass
class test{
private $name;
private $sex;
function __construct(){
$this->aaa='aaa';
}
}
$test=new test();
$reflect=new ReflectionClass($test);
$pro=$reflect->getDefaultProperties();
print_r($pro);//打印结果:Array ( [name] => [sex] => )
echo $test->aaa;//打印结果:aaa
在这个test类中,声明了两个成员变量$name和$sex,但是在构造函数中,又声明了一个变量$aaa,初始化类,使用反射类打印默认成员属性只有声明的两个成员变量属性,但是打印类的$aaa变量发现还是可以输出结果。
请问类的成员变量不用声明,在函数中声明也是可以的吗,有什么区别?
在你这个例子中,使用ReflectionClass是不恰当的,因为__construct只有在实例化class时,才会执行。
也就是说ReflectionClass更多的是反射类声明时的结构,而不是类实例化后的结构,所以没有输出属性aaa是正确,因为属性aaa确实是(在类声明时)不存在的。
那么怎么看属性aaa呢,应该用ReflectionObject反射实例化后的结构,例如
使用ReflectionObject
<?php
class test{
private $name;
private $sex;
function __construct(){
$this->aaa='aaa';
}
}
$test=new test();
$reflect=new ReflectionObject($test);
$pro=$reflect->getProperties();
print_r($pro);
经过实例化以后,属性aaa才会存在,这时你就能看到属性aaa了
因为php是“动态”语言,所以可以类的成员变量不用声明,在函数中声明也是可以的。
ReflectionMethod
通过ReflectionMethod,我们可以得到Person类的某个方法的信息:
是否“public”、“protected”、“private” 、“static”类型
方法的参数列表
方法的参数个数
反调用类的方法
// 执行detail方法
$method = new ReflectionMethod('Person', 'test');
if ($method->isPublic() && !$method->isStatic()) {
echo 'Action is right';
}
echo $method->getNumberOfParameters(); // 参数个数
echo $method->getParameters(); // 参数对象数组