PHP - define constant inside a class

后端 未结 5 1459
失恋的感觉
失恋的感觉 2020-12-05 03:55

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

....something like Foo::app()->MYCONSTANT;

5条回答
  •  無奈伤痛
    2020-12-05 04:27

    See Class Constants:

    class MyClass
    {
        const MYCONSTANT = 'constant value';
    
        function showConstant() {
            echo  self::MYCONSTANT. "\n";
        }
    }
    
    echo MyClass::MYCONSTANT. "\n";
    
    $classname = "MyClass";
    echo $classname::MYCONSTANT. "\n"; // As of PHP 5.3.0
    
    $class = new MyClass();
    $class->showConstant();
    
    echo $class::MYCONSTANT."\n"; // As of PHP 5.3.0
    

    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"
    

提交回复
热议问题