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"