本文介绍了self :: vs className :: inside static className metods in PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这可能没有任何区别,但个人喜好,但是当阅读各种PHP代码时,我遇到了两种方法访问方法类。

I guess there may not be any difference but personal preference, but when reading various PHP code I come across both ways to access the methods class.

什么区别:

class Myclass
{
    public static $foo;

    public static function myMethod ()
    {
        // between:
        self::$foo;
        // and
        MyClass::$foo;
    }
}


推荐答案

注意:初始版本说没有区别,实际上有)

(Note: the initial version said there was no difference. Actually there is)

确实有一点小差别。 self :: 转发静态调用,而 className :: 则不会。这只适用于PHP 5.3中的。

There is indeed a small diference. self:: forwards static calls, while className:: doesn't. This only matters for late static bindings in PHP 5.3+.

在静态调用中,PHP 5.3+会记住最初调用的类。使用 className :: 使PHP忘记此值(即将其重置为 className ),而 self :: 保存它。考虑:

In static calls, PHP 5.3+ remembers the initially called class. Using className:: makes PHP "forget" this value (i.e., resets it to className), while self:: preserves it. Consider:

<?php
class A {
    static function foo() {
        echo get_called_class();
    }
}
class B extends A {
    static function bar() {
        self::foo();
    }
    static function baz() {
        B::foo();
    }
}
class C extends B {}

C::bar(); //C
C::baz(); //B

这篇关于self :: vs className :: inside static className metods in PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 19:16