Alex Alex - 1 year ago 118
PHP Question

PHP - define constant inside a class

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


(and if called like
to be ignored)

Answer Source

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();

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download