何为反射?字面理解,就是根据到达找到源;在面向对象编程中的反射就是根据对象去找出它所属的类,及类的方法,详情;
首先声明一点,反射在实际开发中用的很少(至少我没用过),但是在编写文档的时候,可以用于文档的生成;用于探索类的内部,比较灵活这是优点,缺点就是破坏了类的封装性,使得一些private方法或者属性暴露出来,这既是优点也是缺点;
看个例子
<?php /** * Created by PhpStorm. * User: BoHongtao * Date: 2018/10/27 * Time: 20:43 */ class Person{ private $friend; public $name; public $gender; public function say(){ echo $this->name."is ".$this->gender; } public function __construct($nama,$gender){ $this->nama = $nama; $this->gender = $gender; } public function get($name){ if(isset($this->name)) return $this->name; echo "未设置"; } } $person_1 = new Person('Ming','boy'); // 反射获取类的原型 $obj = new ReflectionClass('person'); $className = $obj->getName(); $Methods = $Properties = array(); foreach($obj->getProperties() as $v) { $Properties[$v->getName()] = $v; } foreach($obj->getMethods() as $v) { $Methods[$v->getName()] = $v; } echo "class {$className}\n{\n"; is_array($Properties)&&ksort($Properties); foreach($Properties as $k => $v) { echo "\t"; echo $v->isPublic() ? ' public' : '',$v->isPrivate() ? ' private' : '', $v->isProtected() ? ' protected' : '', $v->isStatic() ? ' static' : ''; echo "\t{$k}\n"; } echo "\n"; if(is_array($Methods)) ksort($Methods); foreach($Methods as $k => $v) { echo "\tfunction {$k}(){}\n"; } echo "}\n";
运行结果
D:\workspace>php Reflection.php class Person { private friend public gender public name function __construct(){} function get(){} function say(){} }
可以看到,我们根据传递的某个对象,就可以得知这个类中的所有属性和方法,哪怕是private