本文介绍了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"

这篇关于PHP - 在类中定义常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-01 01:45