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开发者_JAVA技巧->segment(5);
if($id && $table){
$this->MKaimonokago->changeStatus($table,$id);
}
flashMsg('success',$this->lang->line('kaimonokago_status_changed'));
redirect("$module/admin/index/","refresh");
}
.................
.................
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.
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 e.g. $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.
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);
}
}
精彩评论