我构建了一个函数来为数组充电一些值。问题是我需要从另一个函数获取该数组(在函数内部)。
不知道如何处理参数。
这是我为我的阵列充电的功能:
public function loadStates(){
$states = array(
"Buenos Aires" => "label label-success",
"Catamarca" => "label label-info",
"Chaco" => "label label-warning",
"Chubut" => "label label-danger";
);
return $states;
}
这是另一个函数(我假装调用创建数组的函数,以便我可以加载要在当前函数中使用的数据):
public function countUsers() {
//breadcrumb
$this->data["states"] = loadStates();
var_dump('$this->data["states"]');die();
//$this->data['totUsers'] = UsersDs::getInstance()->count();
//$this->parser->parse('admin/usuarios/totales/totalRegUsers.tpl',$this->data);
}
这些函数在同一个php文件中。我已经删除了所有的函数参数,所以显然这不起作用
答案 0 :(得分:1)
我有两个选项,我马上就会看到(真的有更多,但很难知道你的情况最好)。您可以通过引用方法传递数组,也可以从loadStates()
方法返回新数组。
public function loadStates(&$arr) {
$arr = array(
"Buenos Aires" => "label label-success",
"Catamarca" => "label label-info",
"Chaco" => "label label-warning",
"Chubut" => "label label-danger"
);
}
public function countUsers(){
$this->loadStates($this->data["states"]);
var_dump($this->data["states"]);die();
}
public function loadStates() {
return array(
"Buenos Aires" => "label label-success",
"Catamarca" => "label label-info",
"Chaco" => "label label-warning",
"Chubut" => "label label-danger"
);
}
public function countUsers(){
$this->data["states"] = $this->loadStates();
var_dump($this->data["states"]);die();
}
答案 1 :(得分:0)
你有几种选择....
public function loadStates(){
return array(
"Buenos Aires" => "label label-success",
"Catamarca" => "label label-info",
"Chaco" => "label label-warning",
"Chubut" => "label label-danger";
);
}
每次调用loadStates时,这将重新创建并返回一个数组。
public function loadStates(){
static $states = array(
"Buenos Aires" => "label label-success",
"Catamarca" => "label label-info",
"Chaco" => "label label-warning",
"Chubut" => "label label-danger";
);
return $states;
}
这将在第一次调用函数时创建数组,并在后续调用中返回存储的副本。
public function __construct(){
$this->states = array(
"Buenos Aires" => "label label-success",
"Catamarca" => "label label-info",
"Chaco" => "label label-warning",
"Chubut" => "label label-danger";
);
}
然后在你的代码中
$this->data["states"] = $this->states();
static protected $states;
public function __construct(){
if (!is_array(self::$states))
self::$states = array(
"Buenos Aires" => "label label-success",
"Catamarca" => "label label-info",
"Chaco" => "label label-warning",
"Chubut" => "label label-danger";
);
}
然后,当您想要使用这样的使用语法访问该属性时:
self::$states["Buenos Aires"]
还有其他几个选项,但应该使用的选项完全取决于您的特定用例。