Rumah > pembangunan bahagian belakang > tutorial php > php 的反射详解及实例分析

php 的反射详解及实例分析

墨辰丷
Lepaskan: 2023-03-29 08:08:01
asal
1510 orang telah melayarinya

本文主要介绍PHP的反射内容的知识,这里提供相关的资料讲解,及简单示例代码供大家参考,有兴趣的小伙伴可以参考下

 最近在看java编程思想,看到类型信息这一章,讲到了类的信息以及反射的概念。顺便温故一下php的反射东西。手册是这样说的:"PHP 5 具有完整的反射 API,添加了对类、接口、函数、方法和扩展进行反向工程的能力。 此外,反射 API 提供了方法来取出函数、类和方法中的文档注释。"当然手册上说的有些抽象!所谓的逆向说白就是能获取关于类、方法、属性、参数等的详细信息,包括注释! 文字总是那么枯燥,举个例子

class Foo {
  public  $foo = 1;
  protected $bar = 2;
  private  $baz = 3;
  
  /**
   * Enter description here ...
   */
  public function myMethod()
  {
    echo 'hello 2b';
  }
}

$ref = new ReflectionClass('Foo');
$props = $ref->getProperties();
foreach ($props as $value) {
  echo $value->getName()."\n";
}

//output
//foo 
//bar
//baz
Salin selepas log masuk

ReflectionClass 这个类返回时某个类的相关的信息,比如 属性,方法,命名空间,实现那些接口等!上个例子中ReflectionClass:: getProperties 返回是 ReflectionProperty 对象的数组。

ReflectionProperty 类报告了类的属性的相关信息。比如 isDefault isPrivate isProtected isPublic isStatic等,方法getName 是获取属性的名称!

以上是获取属性的,还有获取类方法的比如

class Foo {
  public  $foo = 1;
  protected $bar = 2;
  private  $baz = 3;
  
  /**
   * Enter description here ...
   */
  public function myMethod()
  {
    echo 'hello 2b';
  }
}

$ref = new ReflectionClass('Foo');
$method = $ref->getMethod('myMethod');
$method->invoke($ref->newInstance());
Salin selepas log masuk

ReflectionClass::getMethod 是反是一个 ReflectionMethod 类型 ,ReflectionMethod 类报告了一个方法的有关信息,比如 isAbstract isPrivate isProtected isPublic isStatic isConstructor,还有一个重要的方法Invoke,InvokeArgs 就是执行方法!

其他的对象可以看看手册,不是很难!

那反射究竟有哪些用途?

反射是一个动态运行的概念,综合使用他们可用来帮助我们分析其它类,接口,方法,属性,方法和扩展。还可构建模式,比如动态代理。在一些php框架中使用反射也是很经常,比如kohana,yii,下面是kohana 的实现mvc的代码,就是用到了反射!

// Start validation of the controller
$class = new ReflectionClass(ucfirst(Router::$controller).'_Controller');
// Create a new controller instance
$controller = $class->newInstance();
// Load the controller method
$method = $class->getMethod(Router::$method);
// Execute the controller method
$method->invokeArgs($controller, $arguments);
Salin selepas log masuk

上面的代码可以清晰看到这个框架的流程!通过Router 其实就处理url的类,通过Router可以获取哪个控制器、哪个方法!然后再执行方法!

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐:

php微信公众平台交互与接口详解

php实现文件上传详解

php微信公众号js-sdk开发应用

Atas ialah kandungan terperinci php 的反射详解及实例分析. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan