This paper addresses

Share the outline :

  1. Introduce

  2. Specific examples

    2.1  establish Persion class

    2.2  Reflection process

    2.3  Use after reflection

1. Introduce


  -- PHP5 A new feature has been added :Reflection. This function makes phper Sure reverse-engineer class, interface,function,method and extension. adopt PHP Code , You can get something object All the information about , And can interact with it .
  -- What is reflex ?
It means in PHP In operation , Extended analysis PHP Program , Export or extract information about classes 、 Method 、 attribute 、 Parameters, etc , Including comments . This function of dynamically obtaining information and dynamically calling methods of objects is called reflection API. Reflection manipulates the metamodel in the object-oriented paradigm API, It's very powerful , Can help us build complex , Scalable applications .
Its uses are as follows : Automatically load plug-ins , Automatically generate documents , It can even be used to expand PHP Language .
php Reflection api It consists of several classes , It can help us access the metadata of the program or interact with related annotations . With the help of reflection, we can obtain such information as the methods implemented by the class , Create an instance of a class ( Different from using new establish ), Call a method ( It's also different from regular calls ), Pass parameters , Dynamically calling static methods of a class .
      Reflection api yes php The built-in oop Technology expansion , Including some classes , Exceptions and interfaces , Combined, they can be used to help us analyze other classes , Interface , Method , attribute , Methods and extensions . these oop Extension is called reflection .
      adopt ReflectionClass, We can get Person Class :
     1) Constant Contants
     2) attribute Property Names
     3) Method Method Names static state
     4) attribute Static Properties
     5) Namespace Namespace
     6)Person Whether the class is final perhaps abstract

2. Specific examples


Create a Person class , And then use ReflectionClass Reflect it
 
   2.1)【 establish Persion class 】

    

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;
publicfunction 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;
}
}

Persion

  2.2)【 Reflection process 】
Next, reflect it , Just put the class name "Person" Pass to ReflectionClass That's all right. :

 
     $class = new ReflectionClass('Person');// establish  Person The reflection class of this class 
$instance = $class->newInstanceArgs($args);// Equivalent to instantiating Person class

  2.3)【 Use after reflection 】

    2.3.1) get attribute (Properties)

 
    $properties = $class->getProperties();
foreach($properties as $property) {
echo $property->getName()."\n";
}
// Output :
// _allowDynamicAttributes
// id
// name
// biography

By default ,ReflectionClass Will get all the attributes ,private and protected Of course . If you just want to get private attribute , You need to send an extra parameter :
$private_properties = $class->getProperties(ReflectionProperty::IS_PRIVATE);
List of available parameters :
               ReflectionProperty::IS_STATIC
               ReflectionProperty::IS_PUBLIC
               ReflectionProperty::IS_PROTECTED
               ReflectionProperty::IS_PRIVATE
      If you want to get it at the same time public and private attribute , Just write :ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED.
    adopt $property->getName() You can get the property name .

    2.3.2)【 Get comment 】

   adopt getDocComment Can get written to property Notes .

 
     foreach($propertiesas$property) {
if($property->isProtected()) {
$docblock = $property->getDocComment();
preg_match('/ type\=([a-z_]*) /', $property->getDocComment(), $matches);
echo$matches[1]."\n";
}
}
// Output:
// primary_autoincrement
// varchar
// text

    2.3.3)【 Method to get the class 】

     Access method (methods): adopt getMethods() To get all of the methods.

    2.3.4)【 Methods that execute classes 】

 
         $instance->getBiography(); // perform Person  The method in getBiography
// perhaps :
$ec=$class->getmethod('getName'); // obtain Person Class getName Method
$ec->invoke($instance); // perform getName Method

【 Tamp PHP Basics 】PHP More articles on the reflection mechanism of

  1. 【java Basics 】Java The reflex mechanism

    One . Knowledge needed in advance (java virtual machine )  1)java Method area of virtual machine :  java The virtual machine has a runtime data area , This data area is divided into method area , Stack area and stack area , The main thing we need to know here is the method area . The main function of method area is to save ...

  2. Java Reflection mechanism application practice

    Reflection basis Before applying the reflection mechanism , First, let's look at how to get the reflection class corresponding to an object Class, stay Java There are three ways to get the reflection class of an object . adopt getClass Method stay Java in , every last Object ...

  3. IO And reflection mechanism

    IO And reflection mechanism One .file class : Belong to java.io In bag kkb effect : Operate on files or directories file You can represent a file , It can also represent a directory , It can also indicate the drive letter . It can be used to manipulate files . file The construction commonly used in ...

  4. Tamp Java Basics ( The 21st )——Java The reflex mechanism

    1. An overview of reflection mechanism Java Reflection mechanism refers to the running state of a program , For any class , We all know all the properties and methods of this class ( Include private.protected etc. ). For any object , We're all able to do some research on its properties and methods ...

  5. java Basic knowledge of ( 11、 ... and )java The reflex mechanism ( On )

    java.lang.Class Class explanation java Class Class explanation One .class class Class Class is java Implementation of a specific class defined by a language , stay java Each class in has a corresponding Class object , In order to java Program runtime ...

  6. Black horse programmer _Java Basics : The reflex mechanism (Reflection) summary

    ------- android train .java train . Looking forward to communicating with you ! ---------- Reflected in java It's of great significance , It's a dynamic correlation mechanism , It can be loaded at run time . Ascertain . Using nothing known during compilation clas ...

  7. java The reflex mechanism ( Basic Edition )

    package com.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import ja ...

  8. JAVA The basic concept of reflection mechanism

    The reflex mechanism : The so-called reflex mechanism is java Language has a self-awareness ability at runtime . Through this ability, we can thoroughly understand our own situation and prepare for the next action . Here is a specific introduction java The reflection mechanism of . Here you will subvert the original right java The understanding of the . J ...

  9. Java Develop the reflection mechanism of training basic knowledge analysis

    Java It's an old programming language , Is one of the most widely used programming languages . Want to learn Java You have to master Java Basic knowledge of , And reflection for beginners Java It's absolutely a very important knowledge point for the people in the world . What is reflection ? How to understand the mechanism of reflection ? How to use reflection ...

  10. java Basics —— The reflex mechanism

    What is the reflection mechanism The reflection mechanism is in the running state , For any class , Can know all the properties and methods of this class : For any object , Can call any of its methods and properties : The function of dynamically obtaining information and dynamically calling methods of objects is called jav ...

Random recommendation

  1. LINQ series :Linq to Object Limit operators

    1. Where Limit operators Where For filtering sequence , Filter the data in the sequence according to the logic provided .Where Can appear many times . 1.1 Prototype definition public static IEnumerable<TSou ...

  2. PHP Arrays and simple functions

    PHP function : 1. Simple functions Four elements : Return type , Function name , parameter list , The body of the function function Show() { echo "hello"; } Show(); Running results :hellow ...

  3. What is? ValueStack

    Reprinted from :http://www.cnblogs.com/zyw-205520/archive/2012/09/12/2681346.html Strut2 Of Action Class can get all the relevant values through attributes , Such as ...

  4. UOJ265 【NOIP2016】 Angry birds

    The copyright of this article belongs to ljh2000 And blog park , Welcome to reprint , But keep this statement , And give a link to the original , Thank You for Your Cooperation . The author of this article :ljh2000 The author blog :http://www.cnblogs.com/ljh2000-jump/ turn ...

  5. Linggle: English writing learning search engine

    Linggle Search engine is a grammar that can be used in English writing . Sentence tools , It can help learners analyze more accurate English writing suggestions , Be able to infer short sentences and sentences according to part of speech , Can accurately share the complete English sentence how to write . Linggle It's an academic team in Taiwan ...

  6. Sprint( Fifth day 11.18)

  7. VMware vSphere 5.5 Of 12 It's an update (1)

    [IT Expert network virtualization ] stay VMworld 2013 Issued at the conference VMware vSphere 5.5 Version provides enhancements and improvements , Across from hypervisor To manage the entire stack , Promoted VMware Performance of . Scalability and availability ...

  8. use ToggleButton and ImageView Realize the switch of display in different states

    by , The first time I wrote it because I put implements OnCheckedChangeListener The interface implemented here is wrongly written , It's been a long time , Later I found that these two sentences were missing btn = (ToggleButton) fin ...

  9. string.format Complete works of

    The numeric format of a string stringstr1 =string.Format("{0:N1}",56789);               //result: 56,789.0 strin ...

  10. mysql my.ini Invalid profile modification , modify mysql Default character set

    problem It begins with Use mysql The command can't insert Chinese data ERROR 1366 (HY000): Incorrect string value: '\xD6\xD0\xCE\xC4' for column ...