简体   繁体   中英

How can I avoid repeating variables?

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

How about setting them in the constructor?

function Admin(){
    parent::Shop_Admin_Controller();
    $this->module = $this->uri->segment(4);
    $this->table = "omc_" . $this->module;
    $this->id = $this->uri->segment(5);
}

They can then be used as eg $this->module in the other functions in your class.

This of course presumes that you don't have properties with those names in the parent class. If you do, you use different names.

You could simply add then as instance (ie: 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.

Maybe set them as protected attributes in your constructor?

class Admin
{
    protected $_module;
    protected $_table;
    protected $_id;
    public function __construct()
    {
        // do something that initializes $this->uri;
        $this->_module = $this->uri->segment(4);
        $this->_table = 'omc_' . $module;
        $this->_id = $this->uri->segment(5);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM