PHP - Zend say avoid Magic Methods?

I was reading this page - http://deaduseful.com/blog/posts/50-php-optimisation-tips-revisited

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.

After some Google searching (and winding up here to an unrelated question) I wondered if anyone had any reccomendations on that front?

I use __get() alot in my code, usually to save variables that I don't always use e.g.

I may have a table with name, desc, category_id, time_added

My get would look something like this:

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);
    }
}

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.

Would this be considered bad practice and an extra load on the server?

Often I will extend classes with magic methods and do something like this if the child class doesn't match something in a get.

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);
    }
}

Would this be bad practice and bad for performance? The maximum number of levels I have when extending magic methods is three.

10
задан SamT 26 January 2015 в 04:24
поделиться