一句话儿的事
2020-01-13 00:25:04浏览 1451
反射技术
原理:通过反射类,可以知道一切类信息,从而实现更加健壮的代码
作用:
写底层框架
扩展类功能
管理大量未知类
demo11.php
<?php
namespace Extend;
use ReflectionClass;
use Exception;
/**
* 用户相关类
* Class User
* @package Extend
*/
class User{
const ROLE = 'Students';
public $username = '';
private $password = '';
public function __construct($username, $password)
{
$this->username = $username;
$this->password = $password;
}
/**
* 获取用户名
* @return string
*/
public function getUsername()
{
return $this->username;
}
/**
* 设置用户名
* @param string $username
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* 获取密码
* @return string
*/
private function getPassword()
{
return $this->password;
}
/**
* 设置密码
* @param string $password
*/
private function setPassowrd($password)
{
$this->password = $password;
}
}
$class = new ReflectionClass('Extend\User'); // 将类名User作为参数,即可建立User类的反射类
echo '将类名User作为参数,即可建立User类的反射类';echo "<br/>";
echo "<pre>";var_dump($class);echo "</pre>";echo "<br/>";
$properties = $class->getProperties(); // 获取User类的所有属性,返回ReflectionProperty的数组
echo '获取User类的所有属性,返回ReflectionProperty的数组';echo "<br/>";
echo "<pre>";var_dump($properties);echo "</pre>";echo "<br/>";
$property = $class->getProperty('password'); // 获取User类的password属性ReflectionProperty
echo '获取User类的password属性ReflectionProperty';echo "<br/>";
echo "<pre>";var_dump($property);echo "</pre>";echo "<br/>";
$methods = $class->getMethods(); // 获取User类的所有方法,返回ReflectionMethod数组
echo '获取User类的所有方法,返回ReflectionMethod数组';echo "<br/>";
echo "<pre>";var_dump($methods);echo "</pre>";echo "<br/>";
$method = $class->getMethod('getUsername'); // 获取User类的getUsername方法的ReflectionMethod
echo '获取User类的getUsername方法的ReflectionMethod';echo "<br/>";
echo "<pre>";var_dump($method);echo "</pre>";echo "<br/>";
$constants = $class->getConstants(); // 获取所有常量,返回常量定义数组
echo '获取所有常量,返回常量定义数组';echo "<br/>";
echo "<pre>";var_dump($constants);echo "</pre>";echo "<br/>";
$constant = $class->getConstant('ROLE'); // 获取ROLE常量
echo '获取ROLE常量';echo "<br/>";
echo "<pre>";var_dump($constant);echo "</pre>";echo "<br/>";
$namespace = $class->getNamespaceName(); // 获取类的命名空间
echo '获取类的命名空间';echo "<br/>";
echo "<pre>";var_dump($namespace);echo "</pre>";echo "<br/>";
$comment_class = $class->getDocComment(); // 获取User类的注释文档,即定义在类之前的注释
echo '获取User类的注释文档,即定义在类之前的注释';echo "<br/>";
echo "<pre>";var_dump($comment_class);echo "</pre>";echo "<br/>";
$comment_method = $class->getMethod('getUsername')->getDocComment(); // 获取User类中getUsername方法的注释文档
echo '获取User类中getUsername方法的注释文档';echo "<br/>";
echo "<pre>";var_dump($comment_class);echo "</pre>";echo "<br/>";