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;
(and if called like MYCONSTANT
to be ignored)
A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name).
It is possible to define constants on a per-class basis remaining the same and unchangeable. The default visibility of class constants is public . Note: Class constants can be redefined by a child class.
The property cannot be modified outside the class, such as constants, but unfortunately it is accessed as a method, not as a constant, so the syntax is not the same. (2) If you really want this value to be accessed as constant from outside, you can use define () inside the constructor.
Constant vs VariablesA constant can only be defined using define() function. It cannot be defined by any simple assignment. A variable can be defined by simple assignment (=) operator. There is no need to use the dollar ($) sign before constant during the assignment.
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"
This is and old question, but now on PHP 7.1 you can define constant visibility.
EXAMPLE
<?php class 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:
bar Fatal 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With