PHP - define constant inside a class PHP - define constant inside a class php php

PHP - define constant inside a class


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(); // nullMyClass::showStaticVariable('constant value'); // "constant value"MyClass::showStaticVariable('other constant value?'); // "constant value"MyClass::showStaticVariable(); // "constant value"


This is and old question, but now on PHP 7.1 you can define constant visibility.

EXAMPLE

<?phpclass Foo {    // As of PHP 7.1.0    public const BAR = 'bar';    private const BAZ = 'baz';}echo Foo::BAR . PHP_EOL;echo Foo::BAZ . PHP_EOL;?>

Output of the above example in PHP 7.1:

barFatal error: Uncaught Error: Cannot access private const Foo::BAZ in …

Note: As of PHP 7.1.0 visibility modifiers are allowed for class constants.

More info here


class Foo {    const BAR = 'baz';}echo Foo::BAR;

This is the only way to make class constants. These constants are always globally accessible via Foo::BAR, but they're not accessible via just BAR.

To achieve a syntax like Foo::baz()->BAR, you would need to return an object from the function baz() of class Foo that has a property BAR. That's not a constant though. Any constant you define is always globally accessible from anywhere and can't be restricted to function call results.