摘要:这篇文章主要介绍了php反射机制用法,是php程序设计中比较重要的概念,需要的朋友可以参考下
一、反射是什么
反射是操纵面向对象范型中元模型的API(php5)
通过ReflectionClass,我们可以得到Person类的以下信息:
1)常量 Contants
2)属性 Property Names
3)方法 Method Names静态
4)属性 Static Properties
5)命名空间 Namespace
6)Person类是否为final或者abstract
<? php
classPerson {
public $id;
public $username;
private $pwd;
private $sex;
public function run() {
echo '<br/>running';
}
}
$class = new ReflectionClass('Person'); //建立反射类
$instance=$class->newInstance(); //实例化
print_r($instance); //Person Object ( [id] => [username] => [pwd:Person:private] => [sex:Person:private] => )$properties = $class->getProperties();foreach($properties as $property) {
echo "<br/>" . $property->getName();
}
//默认情况下,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()可以得到属性名。$class->getMethods();
//获取方法(methods):通过getMethods() 来获取到类的所有methods。$instance->run();
//执行Person 里的方法getBiography
//或者:$ec=$class->getmethod('run');
//获取Person 类中的getName方法$ec->invoke($instance);以上就是简述php反射机制实例详解的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号