Thursday, July 31, 2008

Setting read-only variables of PHP classes

Many would ask, how can I make variables of PHP classes read only? There's nothing similar to other programming languages such as C# to use the readonly keyword.

Oh well, there is a work around instead. For example, in the class pClass, there is this variable named $read i want to make read-only. So i will have to do this:


class pClass{

private $read = '';

public function __get($name){ // this will be called when a variable is read.
return $this->$name; // returns the variable
// without this function, PHP will return an error.



Note that by setting this function, all private variables in your class are readable. However, you still can filter them in the __get function before returning the result..

Note that the function have 2 underscores, not one.


TechnoSnack's said...
This comment has been removed by a blog administrator.
Clint Valusek said...

that is an interesting way to do that, as long as you remember __get is very slow. most php performance blogs recommend not using magic methods like __get unless you are not concerned with the performance. a performance recommendation is to make a getter for that particular variable.

also, that doesn't stop them from change the variable if it is an object. you would need to add a if is_object($this->$name) then return clone ($this->$name) i believe

Sankar lp said...

I have read your blog its very attractive and impressive. I like it your blog.

PHP 7 Training in chennai | PHP 7 Training Course

PHP 7 Training in chennai | Online PHP 7 Course