本文实例讲述了php反射学习之不用new方法实例化类操作。分享给大家供大家参考,具体如下:php反射入门示例简单介绍了 php 反射的几个常见类的使用方法,但是用反射能做些什么,你可能还是想象不到,
id = $id; $this->name = $name; } public function study() { echo $this->name.' is learning.....'.PHP_EOL; } public function showBag(){ echo "My bag have ".$this->bag->all(); } }isInstantiable()) { throw new Exception("类{$class} 不存在"); } $constructor = $ref->getConstructor(); if(is_null($constructor)) { return new $class; } $params = $constructor->getParameters(); $resolveParams = []; foreach ($params as $key=>$value) { $name = $value->getName(); if(isset($vars[$name])) { $resolveParams[] = $vars[$name]; } else { $default = $value->isDefaultValueAvailable() ? $value->getDefaultValue() : null; if(is_null($default)) { if($value->getClass()) { $resolveParams[] = make($value->getClass()->getName(), $vars); } else { throw new Exception("{$name} 没有传值且没有默认值。"); } } else { $resolveParams[] = $default; } } } return $ref->newInstanceArgs($resolveParams); }根据 Student 的构造函数的参数不同有几种情况:(以下代码,请按不同情况追加到 run.php 中运行)
try { $stu = make('Student', ['id' => 1]); print_r($stu); $stu->study(); } catch (Exception $e) { echo $e->getMessage(); }情况二 提供了 $name 的值
try { $stu = make('Student', ['id' => 1, 'name' => 'li']); print_r($stu); $stu->study(); } catch (Exception $e) { echo $e->getMessage(); }id = $id; $this->name = $name; $this->bag = $bag; } public function study() { echo $this->name.' is learning.....'.PHP_EOL; } public function showBag(){ echo "My bag is ".$this->bag->name(); } }这时候运行一下
1, 'name' => 'li']); print_r($stu); $stu->study(); $stu->showBag(); } catch (Exception $e) { echo $e->getMessage(); }更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。