本文实安全期会怀孕吗例讲述了php反射学习之依赖注入。分享给大家供大家参考,具体如下:
先看代码:
<?phpif (php_sapi != 'cli') { exit('plea run it in terminal!');}if ($argc < 3) { exit('at least 2 arguments needed!');}$controller = ucfirst($argv[1]) . 'controller';$action = 'action' . ucfirst($argv[2]);// 检查类是否存在if (!class_exists($controller)) { exit("class $controller does not existed!");}// 获取类的反射$reflector = new reflectionclass($controller);// 检查方法是否存在if (!$reflector->hasmethod($action)) { exit("method $action does not existed!");}// 取类的构造函数$constructor = $reflector->getconstructor();// 取构造函数的参数$parameters = $constructor->getparameters();// 遍历参数foreach ($parameters as $key => $parameter) { // 获取参数声明的类 $injector = new reflectioncla如何辨别假钱ss($parameter->getclass()->name); // 实例化参数声明类并填入参数列表 $parameters[$key] = $injector->newinstance();}// 使用参数列表实例 controller 类$instance = $reflector->newinstanceargs($parameters);// 执行$instance->$action();class hellocontroller{ private $model; public function __construct(testmodel $model) { $this->model = $model; } public街舞考级有必要吗 function actionworld() { echo $this->model->property, php_eol; }}class testmodel{ public $property = 'property';}
(以上代码非原创)将以上代码保存为 run.php
运行方式,在终端下执行php run.php hello world
可以看到,我们要执行 hellocontroller 下的 worldaction,
hellocontroller 的构造函数需要一个 testmodel类型的对象,
通过php 反射,我们实现了, testmodel 对象的自动注入,
上面的例子类似于一个请求分发的过程,是路由请求的分发的一部分,假如我们要接收一个请求 地址例如: /hello/world
意思是要执行 hellocontroller 下的 worldaction 方法。
更多关于php相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《php数组(array)操作技巧大全》、《ph名师教育p基本语法入门教程》、《php运算与运算符用法总结》、《php字符串(strin菊花黄巢g)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家php程序设计有所帮助。
本文发布于:2023-04-07 07:48:42,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/f28be79c948b24d9e4c278bcc622c6f2.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:php反射学习之依赖注入示例.doc
本文 PDF 下载地址:php反射学习之依赖注入示例.pdf
留言与评论(共有 0 条评论) |