3 ms·
Would REEEEEEALLY like to see readonly properties in classes. They had a proposal a while ago to add getter and setter function support, which would be cool an
by dhoulb 13y ago
Would REEEEEEALLY like to see readonly properties in classes.
They had a proposal a while ago to add getter and setter function support, which would be cool and would've allowed it (with some function overhead), but is probably a bit OTT for PHP.
readonly properties would allow you to make truly solid classes. You'd be able to lock them down from outside interference.
Methods could trust that property values hadn't been tampered with from outside, while still providing a way for outside code to read those values extremely quickly, without function overhead.
I think it's an awesome idea, especially since the getter/setter proposal failed. It's very PHPy, and it strikes a nice middle ground between fully public properties and private ones.
External code really shouldn't be able to mess with my class's internal properties anyway, it violates separation of concerns.
- SDGT 13y agoYou can already do this by using a magic setter that blows out an exception whenever its called for whichever variables you denote. A little hacky, but it does indeed prevent setting of certain vars in your classes.
- wvenable 13y agoActually, even easier than SDGT's or krapp's suggestions is to declare your properties private or protected and use a magic getter to expose those properties as public readonly. It's so easy to do that a readonly keyword seems unnecessary.
- krapp 13y agoI agree with you. This is the closest i've been able to get... class whatever{ private $Properties=array(); function __set($key,$val){ try{ if(!isset($this->Properties[$key])){ $this->Properties[$key]=$val; } }catch(Exception $e){ //... } } function __get($key){ try{ if(isset($this->Properties[$key])){ return $this->Properties[$key]; } }catch(Exception $e){ //... } } }
- krapp 13y agoI just noticed some errors in this but the basic gist works... I shouldn't have added the isset checks, those would prevent it from throwing the exceptions -_-
- datphp 13y agoYour code doesn't work... The catch will never be called, and you should never use isset() because it will return false if the value exists but is null. whatever->param = null; whatever->param = 123; Both lines will execute here. function __set($k, $v){ if (array_key_exists($k, $this->Properties)){ throw new ReadOnlyException(); }else{ $this->Properties[$k] = $v; } }
- krapp 13y agoYes, thank you. I noticed the problem after it was too late to edit. Slightly embarrassing.