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".
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 propertyBAR. 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.
This is a pretty old question, but perhaps this answer can still help someone else.
You can emulate a public constant that is restricted within a class scope by applying the final keyword to a method that returns a pre-defined value, like this:
class Foo {
// This is a private constant
final public MYCONSTANT()
{
return 'MYCONSTANT_VALUE';
}
}
The final keyword on a method prevents an extending class from re-defining the method.
You can also place the final keyword in front of the class declaration, in which case the keyword prevents class Inheritance.
To get nearly exactly what Alex was looking for the following code can be used:
final class Constants {
public MYCONSTANT()
{
return 'MYCONSTANT_VALUE';
}
}
class Foo {
static public app()
{
return new Constants();
}
}
The emulated constant value would be accessible like this:
You can define a class constant in php. But your class constant would be accessible from any object instance as well. This is php's functionality.
However, as of php7.1, you can define your class constants with access modifiers (public, private or protected).
A work around would be to define your constant as private or protected and then make them readable via a static function. This function should only return the constant values if called from the static context.
You can also create this static function in your parent class and simply inherit this parent class on all other classes to make it a default functionality.