PHP - 在类中定义常量

2022-01-23 00:00:00 class constants php

如何在类中定义常量,并使其仅在类上下文中调用时可见?

How can I define a constant inside a class, and make it so it's visible only when called in a class context?

....类似于 Foo::app()->MYCONSTANT;

(如果像 MYCONSTANT 那样调用会被忽略)

(and if called like MYCONSTANT to be ignored)

推荐答案

参见类常量:

class MyClass
{
    const MYCONSTANT = 'constant value';

    function showConstant() {
        echo  self::MYCONSTANT. "
";
    }
}

echo MyClass::MYCONSTANT. "
";

$classname = "MyClass";
echo $classname::MYCONSTANT. "
"; // As of PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo $class::MYCONSTANT."
"; // As of PHP 5.3.0

在这种情况下,单独回显 MYCONSTANT 会引发关于未定义常量的通知,并输出转换为字符串的 constant 名称:"MYCONSTANT".

In this case echoing MYCONSTANT by itself would raise a notice about an undefined constant and output the constant name converted to a string: "MYCONSTANT".

编辑 - 也许你正在寻找的是这个 静态属性/变量:

EDIT - Perhaps what you're looking for is this static properties / variables:

class MyClass
{
    private static $staticVariable = null;

    public static function showStaticVariable($value = null)
    {
        if ((is_null(self::$staticVariable) === true) && (isset($value) === true))
        {
            self::$staticVariable = $value;
        }

        return self::$staticVariable;
    }
}

MyClass::showStaticVariable(); // null
MyClass::showStaticVariable('constant value'); // "constant value"
MyClass::showStaticVariable('other constant value?'); // "constant value"
MyClass::showStaticVariable(); // "constant value"

相关文章