Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP - Zend say avoid Magic Methods?
    primarykey
    data
    text
    <p>I was reading this page - <a href="http://deaduseful.com/blog/posts/50-php-optimisation-tips-revisited" rel="nofollow noreferrer">http://deaduseful.com/blog/posts/50-php-optimisation-tips-revisited</a></p> <p>And one of the recommendations was to avoid using Magic Methods, cited from a Zend Performance PDF which gives no reason for its recommendation to avoid them.</p> <p>After some Google searching (and winding up here to an unrelated question) I wondered if anyone had any reccomendations on that front?</p> <p>I use __get() alot in my code, usually to save variables that I don't always use e.g.</p> <p>I may have a table with name, desc, category_id, time_added</p> <p>My get would look something like this:</p> <pre> public function __get($name) { switch($name) { case 'name': case 'desc': case 'category': case 'time_added': $result = do_mysql_query(); $this->name = $result['name']; $this->desc = $result['desc']; $this->category = $result['category']; $this->time_added = $result['time_added']; return $this->{$name}; break; default: throw Exception("Attempted to access non existant or private property - ".$name); } } </pre> <p>This seems like a great way to do things as I only ever get something from the database if it's needed and I can refence things like $article->time_added rather than fiddling around with arrays.</p> <p>Would this be considered bad practice and an extra load on the server?</p> <p>Often I will extend classes with magic methods and do something like this if the child class doesn't match something in a get.</p> <pre> public function __get($name) { switch($name) { case 'name': case 'desc': case 'category': case 'time_added': $result = do_mysql_query(); $this->name = $result['name']; $this->desc = $result['desc']; $this->category = $result['category']; $this->time_added = $result['time_added']; return $this->{$name}; break; default: return parent::__get($name); } } </pre> <p>Would this be bad practice and bad for performance? The maximum number of levels I have when extending magic methods is three.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload