1. 测试类
class Test
{
public function __construct() {}
public $pub = 'a';
private $pri = 'b';
protected $pro = 'c';
static $sta = 'd';
const constant = 1;
public function get_pub()
{
return $this->pub;
}
private function get_pri()
{
return $this->pri;
}
protected function get_pro()
{
return $this->pro;
}
final public function get_final_pub()
{
return $this->pub;
}
final private function get_final_pri()
{
return $this->pri;
}
final protected function get_final_pro()
{
return $this->pro;
}
}
2. get_class_methods( ) 获取类的方法
$obj = new Test();
var_dump(get_class_methods($obj));
结果:
array(3) {
[0]=>
string(11) "__construct"
[1]=>
string(7) "get_pub"
[2]=>
string(13) "get_final_pub"
}
结论:get_class_methods()方法只能获取类的公有方法
3. get_object_vars( ) 获取类的属性
$obj = new Test();
var_dump(get_object_vars($obj));exit;
结果:
array(1) {
["pub"]=>
string(1) "a"
}
结论:get_object_vars()方法只能获取公有属性
4. get_class_vars( ) 获取类的属性
var_dump(get_class_vars('Test'));exit; //注意:这个函数测参数是string类型的
结果:
array(2) {
["pub"]=>
string(1) "a"
["sta"]=>
string(1) "d"
}
结论:get_class_vars()这个方法可以获取公共属性和静态属性
5. 反射
1. getProperties() 获取属性
$reflec_obj = new ReflectionClass('Test');
$properties = $reflec_obj->getProperties();
var_dump($properties);exit;
结果:
array(4) {
[0]=>
&object(ReflectionProperty)#3 (2) {
["name"]=>
string(3) "pub"
["class"]=>
string(4) "Test"
}
[1]=>
&object(ReflectionProperty)#4 (2) {
["name"]=>
string(3) "pri"
["class"]=>
string(4) "Test"
}
[2]=>
&object(ReflectionProperty)#5 (2) {
["name"]=>
string(3) "pro"
["class"]=>
string(4) "Test"
}
[3]=>
&object(ReflectionProperty)#6 (2) {
["name"]=>
string(3) "sta"
["class"]=>
string(4) "Test"
}
}
结论:获取类的公有属性、私有属性、保护属性和静态属性(有可选参数:ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_STATIC)
2. getConstants( ) 获取类常量
$reflec_obj = new ReflectionClass('Test');
$constants = $reflec_obj->getConstants();
var_dump($constants);exit;
结果:
array(1) {
["constant"]=>
int(1)
}
结论:返回类的常量
3. getMethods( ) 获取类的方法
$reflec_obj = new ReflectionClass('Test');
$methods = $reflec_obj->getMethods();
var_dump($methods);exit;
结果:
array(7) {
[0]=>
&object(ReflectionMethod)#5 (2) {
["name"]=>
string(11) "__construct"
["class"]=>
string(4) "Test"
}
[1]=>
&object(ReflectionMethod)#4 (2) {
["name"]=>
string(7) "get_pub"
["class"]=>
string(4) "Test"
}
[2]=>
&object(ReflectionMethod)#3 (2) {
["name"]=>
string(7) "get_pri"
["class"]=>
string(4) "Test"
}
[3]=>
&object(ReflectionMethod)#2 (2) {
["name"]=>
string(7) "get_pro"
["class"]=>
string(4) "Test"
}
[4]=>
&object(ReflectionMethod)#6 (2) {
["name"]=>
string(13) "get_final_pub"
["class"]=>
string(4) "Test"
}
[5]=>
&object(ReflectionMethod)#7 (2) {
["name"]=>
string(13) "get_final_pri"
["class"]=>
string(4) "Test"
}
[6]=>
&object(ReflectionMethod)#8 (2) {
["name"]=>
string(13) "get_final_pro"
["class"]=>
string(4) "Test"
}
}
结论:返回类的所有方法