类的更新----MVC设计模式
1 <?php 2 class stdObject { 3 public function __construct(array $arguments = array()) { 4 if (!empty($arguments)) { 5 foreach ($arguments as $property => $argument) { 6 $this->{$property} = $argument; 7 } 8 } 9 } 10 11 public function __call($method, $arguments) { 12 $arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this). 13 if (isset($this->{$method}) && is_callable($this->{$method})) { 14 return call_user_func_array($this->{$method}, $arguments); 15 } else { 16 throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()"); 17 } 18 } 19 } 20 21 // Usage. 22 23 $obj = new stdObject(); 24 $obj->name = "Nick"; 25 $obj->surname = "Doe"; 26 $obj->age = 20; 27 $obj->adresse = null; 28 29 $obj->getInfo = function($stdObject) { // $stdObject referred to this object (stdObject). 30 echo $stdObject->name . " " . $stdObject->surname . " have " . $stdObject->age . " yrs old. And live in " . $stdObject->adresse; 31 }; 32 33 $func = "setAge"; 34 $obj->{$func} = function($stdObject, $age) { // $age is the first parameter passed when calling this method. 35 $stdObject->age = $age; 36 }; 37 38 $obj->setAge(24); // Parameter value 24 is passing to the $age argument in method 'setAge()'. 39 40 // Create dynamic method. Here i'm generating getter and setter dynimically 41 // Beware: Method name are case sensitive. 42 foreach ($obj as $func_name => $value) { 43 if (!$value instanceOf Closure) { 44 45 $obj->{"set" . ucfirst($func_name)} = function($stdObject, $value) use ($func_name) { // Note: you can also use keyword 'use' to bind parent variables. 46 $stdObject->{$func_name} = $value; 47 }; 48 49 $obj->{"get" . ucfirst($func_name)} = function($stdObject) use ($func_name) { // Note: you can also use keyword 'use' to bind parent variables. 50 return $stdObject->{$func_name}; 51 }; 52 53 } 54 } 55 56 $obj->setName("John"); 57 $obj->setAdresse("Boston"); 58 59 $obj->getInfo(); 60 ?>