<?php class Student { public $id; public $name; public function __construct($id,$name) { $this->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(); } } |
<?php require 'student.php'; function make($class, $vars = []) { $ref = new ReflectionClass($class); if(!$ref->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); } |
try { $stu = make('Student', ['id' => 1]); print_r($stu); $stu->study(); } catch (Exception $e) { echo $e->getMessage(); } |
try { $stu = make('Student', ['id' => 1, 'name' => 'li']); print_r($stu); $stu->study(); } catch (Exception $e) { echo $e->getMessage(); } |
<?php class Bag{ public function name(){ return "学生包".PHP_EOL; } } class Student { public $id; public $name; public function __construct($id, $name="xxx", Bag $bag) { $this->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(); } } |
<?php try { $stu = make('Student', ['id' => 1, 'name' => 'li']); print_r($stu); $stu->study(); $stu->showBag(); } catch (Exception $e) { echo $e->getMessage(); } |