A brief description of the php reflection mechanism and detailed examples

巴扎黑
Release: 2023-03-15 09:50:01
Original
1415 people have browsed it


Abstract: This article mainly introduces the use of PHP reflection mechanism, which is an important concept in PHP programming. Friends who need it can refer to it

1. What is reflection
Reflection is an API for manipulating the meta-model in the object-oriented paradigm (php5)
Through ReflectionClass, we can get the following information of the Person class:
1) Constants Contents
2) Property Property Names
3) Method Names Static
4) Property Static Properties
5) Namespace Namespace
6) Whether the Person class is final or abstract

<? php
   classPerson {
    public $id;
    public $username;
    private $pwd;
    private $sex;
    public function run() {
        echo &#39;<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);
Copy after login

The above is the detailed content of A brief description of the php reflection mechanism and detailed examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template