简体   繁体   English

在PHP上通过自身名称或类名称访问常量之间的区别?

[英]Difference between accessing a constant by self or class name on PHP?

What is the difference, if any, between accessing a constant using self vs class name. 如果使用self与class名称访问常量之间有什么区别(如果有)。

class MyClass {

    const MAGIC_NUMBER = 4;

    protected $number;

    public function __construct()
    {
        $this->number = self::$MAGIC_NUMBER;
    }
}

vs

class MyClass {

    const MAGIC_NUMBER = 4;

    protected $number;

    public function __construct()
    {
        $this->number = MyClass::MAGIC_NUMBER;
    }
}

There is no difference between them. 它们之间没有区别。
Also you should not put $ there: 另外,您不应在其中放置$

const MAGIC_NUMBER = 4;
protected $number;

The examples you gave are invalid, and I think you might be confusing constants and static variables. 您提供的示例是无效的,我认为您可能会混淆常量和静态变量。

Class constants: 类常量:

class MyClass {
    const MAGIC_NUMBER = 4;

    protected $number;

    public function __construct()
    {
        $this->number = self::MAGIC_NUMBER; // or MyClass::MAGIC_NUMBER
    }
}

Static class variables: 静态类变量:

class MyClass2 {
    static $MAGIC_NUMBER = 4;

    protected $number;

    public function __construct()
    {
        $this->number = MyClass2::$MAGIC_NUMBER; // or self::$MAGIC_NUMBER
    }
}

The main difference is that MyClass2::$MAGIC_NUMBER can be changed, while in both cases the values can be accessed without requiring an instance of the class. 主要区别在于可以更改MyClass2 :: $ MAGIC_NUMBER,而在两种情况下都可以在不需要类实例的情况下访问值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM