News Archive
PhpRiot Newsletter
Your Email Address:

More information

magic __get and __set style?

Note: This article was originally published at Planet PHP on 20 December 2010.
Planet PHP

For a long time I've held that __get and __set in PHP were not all that hot A- mostly because it's solely error handling. AThere's no way to deal invoke __get or __set behaviour for properties that are defined on a class. AThat's sort of a beef for another post (I'd started an RFC some time ago on trying to extend that behaviour to defined properties as well as undefined, but didn't finish it, life got in the way, and various other reasons - again, perhaps for another day).

For those who insist on using __get/__set, I *typically* see this sort of style code:

class foo { protected $_holder = array(); public function __set($name,$value) { if($name=='foo') { $this-_holder['foo'] = $value; } if($name=='bar') { $this-_holder['bar'] = $value; } // etc } }

The effect is to cram a bunch of unrelated code in to the __get/__set overloading methods.

Should I need to use __get/__set again, my new approach will be

class foo { protected $__foo; protected $__bar; A public function __set($name,$value) { if(method_exists($this,"set$name")) { $this-{"set$name"}($value); "/

Truncated by Planet PHP, read more at the original (another 5390 bytes)