时间:2021-07-01 10:21:17 帮助过:4人阅读
class Person {
/**
* For the sake of demonstration, we"re setting this private
*/
private $_allowDynamicAttributes = false;
/** type=primary_autoincrement */
protected $id = 0;
/** type=varchar length=255 null */
protected $name;
/** type=text null */
protected $biography;
public function getId()
{
return $this->id;
}
public function setId($v)
{
$this->id = $v;
}
public function getName()
{
return $this->name;
}
public function setName($v)
{
$this->name = $v;
}
public function getBiography()
{
return $this->biography;
}
public function setBiography($v)
{
$this->biography = $v;
}
}
接下来反射它,只要把类名"Person"传递给ReflectionClass就可以了:
$class = new ReflectionClass('Person');//建立 Person这个类的反射类
$instance = $class->newInstanceArgs($args);//相当于实例化Person 类$properties = $class->getProperties();
foreach($properties as $property) {
echo $property->getName()."\n";
}
// 输出:
// _allowDynamicAttributes
// id
// name
// biography默认情况下,ReflectionClass会获取到所有的属性,private 和 protected的也可以。如果只想获取到private属性,就要额外传个参数:
$private_properties = $class->getProperties(ReflectionProperty::IS_PRIVATE);
可用参数列表:
ReflectionProperty::IS_STATIC
ReflectionProperty::IS_PUBLIC
ReflectionProperty::IS_PROTECTED
ReflectionProperty::IS_PRIVATE
如果要同时获取public 和private 属性,就这样写:ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED。
通过$property->getName()可以得到属性名。
通过getDocComment可以得到写给property的注释。
foreach($properties as $property) {
if($property->isProtected()) {
$docblock = $property->getDocComment();
preg_match('/ type\=([a-z_]*) /', $property->getDocComment(), $matches);
echo $matches[1]."\n";
}
}
// Output:
// primary_autoincrement
// varchar
// text获取方法(methods):通过getMethods() 来获取到类的所有methods。
$instance->getBiography(); //执行Person 里的方法getBiography
//或者:
$ec=$class->getmethod('getName'); //获取Person 类中的getName方法
$ec->invoke($instance); //执行getName 方法相关推荐:
PHP反射机制详解
php实现反射机制自动依赖注入详解
PHP基于反射机制实现自动依赖注入的方法详解
以上就是PHP中反射机制详解的详细内容,更多请关注Gxl网其它相关文章!