【很變態】PHP類實例化對象竟然可以訪問類的“靜態(static)方法”!!!


之前發現一個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)方法,但是不能訪問靜態屬性。

<?php
ini_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'); // 輸出 123456

echo $myDog->name; // 發出Notice信息: Undefined property: Dog::$name in ...

?>

 

 

參考資料:http://php.net/manual/zh/language.oop5.static.php


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM