duandao6414 2012-06-22 23:30
浏览 35
已采纳

从类中静态调用实例方法

According to one of the man pages http://www.php.net/manual/en/language.oop5.static.php :

Calling non-static methods statically generates an E_STRICT level warning.

But, this doesn't seem to be the case when the call is made from inside the class:

error_reporting(-1);

class Test {
    private $id;
    function __construct($id) { $this->id = $id; }
    function id() { return $this->id; }

    function __toString() {
        return Test::id()
             . self::id()
             . static::id()
             . static::id()
             . call_user_func('Test::id')
             . call_user_func(array('Test', 'id'));
    }
}
$a = new Test('a');
$b = new Test('b');


echo "$a $b $a"; # aaaaaa bbbbbb aaaaaa
var_dump(error_get_last()); # NULL

Testing with php 5.4

DEMO: http://codepad.viper-7.com/IKp9iX

I believe I've demonstrated:

  • No E_STRICT warning is generated
  • That php magically corrects the static method call to an instance method call(accessing the instance variable id proves this).

edit- I'd like to add that inserting debug_backtrace() into the __toString call yields a call "type" of ->, which means "method call".

Is this a bug, or a documented feature?

  • 写回答

2条回答 默认 最新

  • dongshixingga7900 2012-06-22 23:38
    关注

    I'd say it's a semi-documented feature:

    In non-static contexts, the called class will be the class of the object instance. Since $this-> will try to call private methods from the same scope, using static:: may give different results. Another difference is that static:: can only refer to static properties.

    In other words (as I understood), it can be used to implement late static binding: using self::id() and static::id() may give different results if you call them in some class that extends your Test.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100