duanpanhuo0618 2010-09-03 10:10
浏览 41

PHP - Zend说避免魔术方法?

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.

  • 写回答

3条回答 默认 最新

  • doudan4834 2010-09-03 10:16
    关注

    It's true, they are slower... but the difference is so tiny that speed vs code is a factor. Is it worth worrying about the difference for quicker development and maintenance?

    See magic benchmarks for stats

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料