之前发现一个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)方法,但是不能访问静态属性。

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

相关文章

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。