Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Static Readonly property in class

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...

like image 944
NewProger Avatar asked Dec 07 '11 09:12

NewProger


2 Answers

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"

  1. 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.

  2. 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".

like image 72
KingCrunch Avatar answered Oct 03 '22 14:10

KingCrunch


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.

like image 28
Artefacto Avatar answered Oct 03 '22 14:10

Artefacto