self:: vs className:: inside static className methods in PHP

泄露秘密 提交于 2020-01-01 01:38:09

问题


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.

What is the difference:

class Myclass
{
    public static $foo;

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

回答1:


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

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+.

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



回答2:


With self you can use it within the class and with the "MyClass", as you have, you can reference it externally:

$instance = new Myclass();
$variable = $instance::$foo


来源:https://stackoverflow.com/questions/3481085/self-vs-classname-inside-static-classname-methods-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!