<?php
class Person
{
/**
* 這里是對$_allowDynamicAttributes的注釋信息
*/
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;
}
}
$class = new ReflectionClass('Person'); //建立Person這個類的反射類
$instance = $class->newInstanceArgs(); //相當於實例化Person類
//var_dump($instance);
//1 獲取屬性(Properties):
echo "<h1>獲取屬性</h1>";
$properties = $class->getProperties();
foreach ($properties as &$property)
{
echo $property->getName()."<BR>";
}
//默認情況下,ReflectionClass會取所有的屬性,private 和protected的也可以
//如果只想獲取到private屬性,就要額外傳個參數
//可用參數列表:
// $private_properties = $class->getProperties(ReflectionProperty::IS_PRIVATE);
// 可用參數列表
//ReflectionProperty::IS_STATIC
//ReflectionProperty::IS_PUBLIC
//ReflectionProperty::IS_PROVATE
//ReflectionProperty::IS_PROECTED
//如果要同時獲取public 和private 屬性,就這樣寫:ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED。
echo "<h1>獲取注釋</h1>";
//獲取注釋
foreach($properties as &$property)
{
if($property->isProtected()) ////測試該方法是否為protected
{
$docblock = $property->getDocComment();
preg_match('/ type\=([a-z_]*) /', $property->getDocComment(), $matches);
echo $matches[1]."<BR><BR>";
}
}
//獲取類的方法
//獲取方法(methods):通過getMethods()來獲取到類的所有methods
//執行類的方法
$instance->setBiography(22);
echo $instance->getBiography(); //執行Person里面的方法getBiography
//或者
$ec = $class->getMethod('setName');
$ec->invoke($instance,'xlc');
$ec2 = $class->getMethod('getName');
echo $ec2->invoke($instance);
?>