druzuz321103 2011-03-07 17:14 采纳率: 100%
浏览 33
已采纳

我怎样才能避免重复变量?

In the following code, I have to use $module = $this->uri->segment(4);, table = "omc_".$module; and $id = $this->uri->segment(5); in every function in this class.

How can I avoiding this repetition?

Thanks in advance.

class Admin extends Shop_Admin_Controller {
  function Admin(){
    parent::Shop_Admin_Controller();
    }

    function changeStatus(){
        $module = $this->uri->segment(4);
        $table = "omc_".$module;
        $id = $this->uri->segment(5);

        if($id && $table){
            $this->MKaimonokago->changeStatus($table,$id);
        }
        flashMsg('success',$this->lang->line('kaimonokago_status_changed'));
        redirect("$module/admin/index/","refresh");
    } 
 .................
 .................
  • 写回答

3条回答 默认 最新

  • dth8312 2011-03-07 17:19
    关注

    You could simply add then as instance (i.e.: class level) variables with the appropriate visibility (protected or private) and then initialise them within your constructor.

    By doing this you wouldn't need to initialise them within each method, and would still have a more convenient naming regime.

    For example:

    class Admin extends Shop_Admin_Controller {
    
        private $module;
        private $table;
        private $id;
    
        public function __construct() {
    
            parent::__construct(); 
    
            // Initialise uri class here, unless this is done 
            // in the parent constructor.
    
            $this->module = $this->uri->segment(4);
            $this->table = "omc_".$module;
            $this->id = $this->uri->segment(5);
        }
    
    
        public function changeStatus() {
    
            if($this->id && $this->table) {
                ...
            }
    
        } 
    }
    

    Incidentally, I'd also recommend setting the appropriate visibility on your methods, unless of course you're targeting PHP 4, in which case replace the "private" with "var" in the above example and remove the visibility properties from the methods.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP