search
HomeBackend DevelopmentPHP TutorialApplication examples of reflection in php

  1. /**
  2. * php reflection example
  3. * edit bbs.it-home.org
  4. */
  5. class Person{
  6. public $name;
  7. function __construct($name){
  8. $this->name=$name;
  9. }
  10. }
  11. interface Module{
  12. function execute();
  13. }
  14. class FtpModule implements Module{
  15. function setHost($host){
  16. print "FtpModule::setHost():$hostn";
  17. }
  18. function setUser($user){
  19. print "FtpModule::setUser():$usern";
  20. }
  21. function execute(){
  22. //something
  23. }
  24. }
  25. class PersonModule implements Module{
  26. function setPerson(Person $person){
  27. print "PersonModule::setPerson:{$person->name}n";
  28. }
  29. function execute(){
  30. //something
  31. }
  32. }
  33. class ModuleRunner{
  34. private $configData
  35. =array(
  36. "PersonModule"=>array('person'=>'bob'),
  37. "FtpModule"=>array('host'=>'example.com','user'=>'anon')
  38. );
  39. private $modules=array();
  40. function init(){
  41. $interface=new ReflectionClass('Module');
  42. foreach($this->configData as $modulename=>$params){
  43. $module_class=new ReflectionClass($modulename);//根据配置configData的名称,实例化ReflectionClass
  44. if(!$module_class->isSubclassOf($interface)){//检查反射得到了类是否是$interface的子类
  45. throw new Exception("unknown module type:$modulename");//不是Module子类则抛出异常
  46. }
  47. $module=$module_class->newInstance();//实例化一个FtpModule或者PersonModule对象
  48. foreach($module_class->getMethods() as $method){//获得类中的方法
  49. $this->handleMethod($module,$method,$params);
  50. }
  51. array_push($this->modules,$module);//将实例化的module对象放入$modules数组中
  52. }
  53. }
  54. function handleMethod(Module $module,ReflectionMethod $method,$params){
  55. $name=$method->getName();//获得方法名称
  56. $args=$method->getParameters();//获得方法中的参数
  57. if(count($args)!=1||substr($name,0,3)!="set"){//检查方法必须是以set开头,且只有一个参数
  58. return false;
  59. }
  60. $property=strtolower(substr($name,3));//讲方法名去掉set三个字母,作为参数
  61. if(!isset($params[$property])){//如果$params数组不包含某个属性,就返回false
  62. return false;
  63. }
  64. $arg_class=@$args[0]->getClass;//检查setter方法的第一个参数(且唯一)的数据类型
  65. if(empty($arg_class)){
  66. $method->invoke($module,$params[$property]);
  67. }else{
  68. $method->invoke($module,$arg_class->newInstance($params[$property]));
  69. }
  70. }
  71. }
  72. $test=new ModuleRunner();
  73. $test->init();
  74. ?>
复制代码

二,通过反射获取类的信息:

  1. /**
  2. * php reflection to obtain class information
  3. * edit bbs.it-home.org
  4. */
  5. class ReflectionUtil{
  6. static function getClassSource(ReflectionClass $class){
  7. $path=$class->getFileName();
  8. $lines=@file($path);
  9. $from=$class->getStartLine();
  10. $to=$class->getEndLine();
  11. $len=$to-$from+1;
  12. return implode(array_slice($lines,$from-1,$len));
  13. }
  14. }
  15. $classname="Person";
  16. $path="../practice/{$classname}.php";
  17. if(!file_exists($path)){
  18. throw new Exception("No such file as {$path}");
  19. }
  20. require_once($path);
  21. if(!class_exists($classname)){
  22. throw new Exception("No such class as {$classname}");
  23. }
  24. print ReflectionUtil::getClassSource(new ReflectionClass('Person'));
  25. ?>
复制代码

输出结果:

class Person{ public $age; public $name; function getName(){return "zjx";} function getAge(){return 12;} function __toString(){ $rs=$this->getName(); $rs.="(age".$this->getAge().")"; return $rs; } }


Statement
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft