duanjia4097 2014-04-26 10:09
浏览 51
已采纳

具有魔术方法,全局数组或..的类?

I downloaded a very simple MVC, and I am converting it to how I like it to be.

I see that in the index.php entry point file, a register object (class code below) is instantiated and a template and router object are passed to it that will be accessible globally in the MVC architecture.

What is the difference with just using a global array instead? Isn't that simpler? Or is there an even better way of handling this?

I'm just looking for what would be a better way of passing these objects.

I have read that magic methods are not good because it's hard to debug and re-factor. But I have read similar things about global arrays.

Class Registry {
    private $vars = array();

    public function __set($index, $value) {
        $this->vars[$index] = $value;
    }

    public function __get($index) {
        return $this->vars[$index];
    }
}
  • 写回答

1条回答 默认 最新

  • duanhanglekr37902 2014-04-28 11:01
    关注

    If your question is just about "what's with this Registry class, is it better than an array?" then: this class is just a wrapper around an array, it's useless. IMO it's because someone thought that using classes instead of arrays automatically makes their code object oriented (which is wrong). Or maybe he/she just wanted to give the array a fancy name to make its purpose clearer (Registry).

    You can drop that class and use an array instead if you want to, you won't loose anything.

    Or if you want to do even better, you can start to learn about dependency injection and DI containers (which is an alternative pattern to the "registry" pattern == global array).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来