php反射特性的演示

关于php的反射特性的文档是极少的,为了大家方便,本人特编写下面一段演示代码,供需要者参考
<?php
  class A{
    public static $type='class';
    const good='I am good';
    public $uid='';
    public $lang='en_US';
    
    public function display($a,$b,$c){
      echo "Method:::I recieved all the parameters in display:\n";
      print_r(func_get_args());
    }
    public static function staticDisplay($a,$b,$c){
      echo "Method:::I recieved all the parameters in staticDisplay:\n";
      print_r(func_get_args());  
    }
  }//end class
  
  $name = 'A';
  $method_name = 'display';
  $static_method_name = 'staticDisplay';
  $params    = array('lang','b','c');
  
  //获取到反射类
  $reflectionClass = new ReflectionClass($name);
  //声明反射类的实例
        $pluginInstance = $reflectionClass->newInstance();
  //对类中所有的静态对象赋值
  foreach ($reflectionClass->getProperties(ReflectionProperty::IS_PUBLIC + ReflectionProperty::IS_PROTECTED) as $prop) {
            $prop->setValue($reflectionClass,'My static value is '.$prop->getName());
         }
  //对类中所有的动态对象赋值
  foreach ($reflectionClass->getProperties(ReflectionProperty::IS_PUBLIC + ReflectionProperty::IS_PROTECTED) as $prop) {
            $prop->setValue($pluginInstance,'My property value is '.$prop->getName());
         }
  
  //实例化两个反射方法
  $reflectionMethod = $reflectionClass->getMethod($method_name);
  $reflectionStaticMethod = $reflectionClass->getMethod($static_method_name);
  
  //输出类和类对象的内容
  echo "A::good --->".A::good."\n";
  echo 'A::$type--->'.A::$type."\n";
  print_r($reflectionClass);
  print_r($pluginInstance);


  //得到某个方法中名称为a的参数
  $reflectionParameter = new ReflectionParameter(array($pluginInstance, $method_name),'a');
  //输出该参数所在的定义的方法和是否引用传递
  echo "\n\n\nParameters test declared function:::\n";
  print_r($reflectionParameter->getDeclaringFunction());
  echo "\nParameters test is passed by reference:::";
  print_r(($reflectionParameter->isPassedByReference()?1:0));
  echo "\n\n\n";
  
  //执行两个反射方法
  $result1 = $reflectionStaticMethod->invokeArgs($reflectionClass,$params);
  $result2 = $reflectionMethod->invokeArgs($pluginInstance,$params);

你可能感兴趣的:(PHP,反射,职场,休闲)