Re: Re: __get, __set, __clone
| From: | Marek Kilimajer | Date: | Wed, 09 Jul 2003 15:27:49 +0000 |
| Subject: | Re: Re: __get, __set, __clone | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-154570@lists.php.net to get a copy of this message | ||
Yann Larrivee wrote:
Hi Greg, thanks for the example. I think i now understand a bit more. I just need a confirmation on this $table->FirstName = 'Greg'; $table->LastName = 'Beaver'; This will actually call __set and it will create a member variable named FristName with the value Greg. Not necessarily. __set is called only if it is defined. You can implement __set the way that you will throw an error if FirstName is being set to 'Greg':class Table { private $properties; function __set($name, $value) { switch($name) { case 'FirstName': if($value=='Greg') { echo "Table: Warning: Greg is forbidden here!"; return; } if($value=='') { echo "Table: Warning: FirstName cannot be empty!"; return; } break; default: echo "Table: Warning: Unknown property '$name'!"; return; } $this->properties[$name]=$value; } }
And if you call $table->FirstName and it is not set it will return false right ? Again, here is called the __get method (if defined). And again if implemented, it can return anything.
SO what are the advantages to use __get, __set.You have more control over the state of your object, your properties cannot be set to something you don't want. You can also create properties on the fly with the __get method.