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条)

报告相同问题?