扒了扒之前的雲筆記,發現了一些很有意思的筆記,下面是一段php程式,可以動態新增成員函數以及成員變數。是之前在php手冊上看到的,感覺很有意思,分享給大家。
//整個類同過閉包以及魔法方法動態添加了一系列的全域變數以及函數,在編程過程中對擴充一個方法是非常有用的//構造方法中表示在構造的時候可以傳入一個數組,同事數組的索引值為屬性名稱,值為屬性值//__call方法表示對沒有的方法時調用此方法 $argument) { $this->{$property} = $argument; } } }//魔法方法,當沒有調用的函數是回調此方法 public function __call($method, $arguments) { //將對象本身作為參數的第一個值合并到參數中 $arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).//判斷是否存在調用的模組,如果存在判斷是否可以調用,如果可以調用,將模組(函數)名,和參數通過call_user_func_array()去執行函數 if (isset($this->{$method}) && is_callable($this->{$method})) { return call_user_func_array($this->{$method}, $arguments); } else { throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()"); } }}// Usage.$obj = new stdObject();//定義類中的全域變數$obj->name = "Nick";$obj->surname = "Doe";$obj->age = 20;$obj->adresse = null;//定義的一個閉包函數$obj->getInfo = function($stdObject) { // $stdObject referred to this object (stdObject). echo $stdObject->name . " " . $stdObject->surname . " have " . $stdObject->age . " yrs old. And live in " . $stdObject->adresse;};$func = "setAge";$obj->{$func} = function($stdObject, $age) { // $age is the first parameter passed when calling this method. $stdObject->age = $age;};//調用閉包函數$obj->setAge(24); // Parameter value 24 is passing to the $age argument in method 'setAge()'.// Create dynamic method. Here i'm generating getter and setter dynimically// Beware: Method name are case sensitive.//迴圈取出對象中的函數/變數名,分別動態產生對應的set和get函數foreach ($obj as $func_name => $value) { if (!$value instanceOf Closure) { $obj->{"set" . ucfirst($func_name)} = function($stdObject, $value) use ($func_name) { // Note: you can also use keyword 'use' to bind parent variables. $stdObject->{$func_name} = $value; }; $obj->{"get" . ucfirst($func_name)} = function($stdObject) use ($func_name) { // Note: you can also use keyword 'use' to bind parent variables. return $stdObject->{$func_name}; }; }}//調用函數$obj->setName("John"); //會首先調用__call函數,之後會回調到閉包函數定義的地方$obj->setAdresse("Boston");$obj->getInfo();?>
以上就介紹了php實現一段非常有意思的代碼(可擴充),包括了方面的內容,希望對PHP教程有興趣的朋友有所協助。