My problem is: I need to overload standard get and set for static variables in class... but no such functionality provided in php... it was asked in 2008 and still not implemented... Same goes for readonly...
My question: is there a way to make a static property accesible for reading from outside, but protected from modification?
echo aaa::$qwe; //<--- echoes value of $qwe
aaa::$qwe = '666'; //<--- throws an error because variable is protected from modification
I can't use const because some variables contain arrays.
Maybe there are some workarounds?
Yeah, I know I can make it like aaa::Get('qwe') but that's no good...
Directly answering your question: No, you cannot mark regular properties as readonly. If you want to set primitive types (except array
), that will never change, you should use constants
const QWE = '666';
That doesn't work for objects and arrays. I see two (lets say) "solutions"
Use Getter
private $qwe;
public function getQwe() { return $this->qwe; }
protected function setQwe($value) { $this->qwe = $value; }
I don't like them very much ("Properties define the state, not the behavior, like methods do"). You always get twice as much additional methods as properties and if you have many properties, this will extremely blow up your class. However, it's as far as I can see the only way to implement what you want to achieve.
Trust your users ;) Comment your property and say something like "If you change this value, probably something will break and its your very own fault".
/**
* QWE
*
* This property should be treatened as "readonly". If you change this value
* something scary will happen to you.
*
* @readonly
* @var string
*/
public $qwe = '666';
Its not great, but at least you can say "I told you".
If the value never changes, you can use const
instead.
Otherwise, there's no way that satisfies your restrictions (short of hooking function calls in PHP through an extension, but even then you'd need to change your static variable accesses to function calls; otherwise, you'd have to patch PHP).
Of course, it's highly doubtful that what your application is doing is good design. Relying on changing static properties is more or less the same as relying on global variables.
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