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

  • 相关阅读:
    176. Second Highest Salary
    175. Combine Two Tables
    172. Factorial Trailing Zeroes
    171. Excel Sheet Column Number
    169. Majority Element
    168. Excel Sheet Column Title
    167. Two Sum II
    160. Intersection of Two Linked Lists
    个人博客记录
    <meta>标签
  • 原文地址:https://www.cnblogs.com/52php/p/5669977.html
Copyright © 2011-2022 走看看