Hi,
my 2c:
1) it shouldn't replace the visibility definition: we could also have
protected readonly properties.
2) It only requires a bit of discipline, not to edit the properties you
want to be readonly.
3) how would you check if the property if readonly ? Trying it could
result to a Fatal error as you wanted. You would then need a
isReadonly() method/function: the function call wouldn't be spared.
4) if you're looking for strong performances, use (2) and don't care
about readonly.
Such code would be a way to emulate them in userland, which produces
overhead of course, but probably less than your switch:
class foo
{
protected $_readonlyVars = array('name1' => true, 'name2' => false);
protected $_vars = array('name1' => 'value1', 'name2'
=>
'value2');
public function __set($name, $value)
{
if(empty($this->_readonlyVars[$name])) {
$this->_vars[$name] = $value;
}
}
public function __get($name)
{
if(isset($this->_vars[$name])) {
return $this->_vars[$name];
}
}
}
$o = new foo;
$o->name1 = $o->name2 = 'newvalue';
echo $o->name1,'-', $o->name2; // value1-newvalue
Jason Garber a écrit :
> Hello internals,
>
> __get() and __set() are great, but 90% of the time, I find myself
> using them to create public readonly properties.
>
> The only problem with this is it is horridly inefficient, consuming
> at least 1 function call and one switch statement (or equiv) per
> property read.
>
> Would it be possible to create a new object property attribute:
> readonly
>
> class xx
> {
> readonly $bar;
> }
>
> $o = new xx();
>
> $o->bar = 10;
> >>> FATAL ERROR
>
>
> This way, PHP would allow reading (as if it were public), but only
> allow writing from within the class.
>
> I think it could really boost performance of complicated application
> logic that wishes to enforce good visibility.
>
> Comments?
>
> PS. What brought this up was some serious performance issues in a
> piece of code that I am working with - most of which can be tied
> back to __get() performance.
>
>
--
Etienne Kneuss
http://www.colder.ch/
[email protected]