Well in theory you could build a read-only class in a static context.
John S.A.
class StaticReadOnly {
private static $value;
private static $hasBeenSet = false;
public static function get() {
return self::$value;
}
public static function set($value) {
if (self::$hasBeenSet === false) {
self::$value = $value;
self::$hasBeenSet = true;
}
}
}
StaticReadOnly::setOnce(12);
var_dump(StaticReadOnly::get());
this is ofc not as performant as a normal class constant.
so another way would be just using define
class ConstFactory {
public const NAME_PREFIX = 'my-fancy-prefix-';
public function create(string $name, $value): void {
if (!defined($name)) {
define(self::NAME_PREFIX . $name, $value);
}
}
}
it's also possible to set a local static in a function / method body. this will be set only once.
I usually use this as a local cache
class LocalStatic {
public function myMethod($val1, $val2, $staticVal) {
static $static;
if (!$static) {
$static = $staticVal;
}
}
}
does this help?
j
stuff ;)
a static property should be possible to change. in the PHP it just means 'global' not like in other languages.
A const however is defined as 'constant' which means setting it in a class and not an object context to my knowledge is not possible in a common way. So basically 'namespaced globals'
you could however use 'define' and just set it as a generated global constant. or you could have a look at reflections or the php AST and just create it dynamically.
But since they are 'dynamic' to some degree I would recommend using a static variable.
And __callStatic only works with methods since it's only works within objects and objects have a context hence they are not functions.