zoukankan      html  css  js  c++  java
  • 【很变态】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

  • 相关阅读:
    使用HttpModule实现权限系统
    Asp.net的HTTP请求处理过程
    Asp.net的HTTP请求处理过程
    IHttpModule
    HttpModule内部事件机制和生命周期
    java 窗口中的动态效果
    first
    判断素数
    螺旋矩阵
    JavaBean笔记
  • 原文地址:https://www.cnblogs.com/52php/p/5669977.html
Copyright © 2011-2022 走看看