標籤:
之前發現一個PHP的變態問題:PHP中靜態(static)調用非靜態方法詳解
這次看了下 ThinkPHP 的源碼 function.inc.php ,裡面有個函數:
/** * 取得對象執行個體 支援調用類的靜態方法 * * @param string $name 類名 * @param string $method 方法 * @param string $args 參數 * @return object 對象執行個體 */function get_instance_of($name, $method = ‘‘, $args = array()) {static $_instance = array();$identify = empty($args) ? $name . $method : $name . $method . to_guid_string($args);if (!isset($_instance[$identify])) {if (class_exists($name)) {$o = new $name();if (method_exists($o, $method)) {if (!empty($args)) {$_instance[$identify] = call_user_func_array(array(&$o, $method), $args);} else {$_instance[$identify] = $o->$method();}} else {$_instance[$identify] = $o;}} else {halt(L(‘_CLASS_NOT_EXIST_‘) . ‘:‘ . $name);}}return $_instance[$identify];}
該函數注釋說可以 支援調用類的靜態方法,從源碼錶面看,按理說類執行個體是不能調用類的靜態方法。可是呢,PHP偏偏就支援 類執行個體化對象可以訪問靜態(static)方法,但是不能訪問靜態屬性。
<?phpini_set(‘display_error‘, true);error_reporting(E_ALL);class Dog {public static $name = ‘wangwang‘;static function say($data) {echo $data;}}$myDog = new Dog();$myDog->say(‘123456‘); // 輸出 123456echo $myDog->name; // 發出Notice資訊: Undefined property: Dog::$name in ...?>
參考資料:http://php.net/manual/zh/language.oop5.static.php
【很變態】PHP類執行個體化對象竟然可以訪問類的“靜態(static)方法”!!!