<?php
/*反射:面向对象编程中对象被赋予了自省的能力,而这个自省的过程就是反射
通俗的话来说就是 我给你一个光秃秃的对象,我仅仅通过这个对象就能找到它所属的类、拥有的方法。
*2014-3-25
例子说明:如何使用反射API
*/
class person{
public $name;
public $gender;
public function say(){
echo $this->name,"\tis",$this->gender,"\r\n";
}
public function __set($name,$value){
echo "Setting $name to $value";
$this->$name=$value;
}
public function __get($name){
if(!isset($this->name)){
echo '未设置';
$this->$name='现在为你设置默认值';
}
return $this->$name;
}
}
$student = new person();
$student->name="Tom";
$student->gender="male";
$student->age=24;
//现在根据$student怎么来获取这个对象的相关方法属性呢?
$reflect = new ReflectionObject($student);
$props = $reflect->getProperties();
foreach($props as $prop){
print $prop->getName()."\n";
}
$m = $reflect->getMethods();
foreach($m as $prop){
print $prop->getName()."\n";
}
/*输出
*Setting age to 24 name gender age say __set __get
*/
//这里也介绍一下不用反射的办法
//返回对象属性的关联数组
var_dump(get_object_vars($student));
/*
*array(3) {
["name"]=>
string(3) "Tom"
["gender"]=>
string(4) "male"
["age"]=>
int(24)
}
*/
//类属性
var_dump(get_class_vars(get_class($student)));
/*
*array(2) {
["name"]=>
NULL
["gender"]=>
NULL
}
*/
//返回类的方法名所组成的数组
var_dump(get_class_methods(get_class($student)));
/*
*array(3) {
[0]=>
string(3) "say"
[1]=>
string(5) "__set"
[2]=>
string(5) "__get"
}
*/
//这种方法显然没有反射API功能强大,关于反射的更多 未完待续.......
?>