【发布时间】:2016-08-12 15:32:58
【问题描述】:
我已经说明了我的定制 MV,我有一个简单的模型 + 控制器类,当被不同的函数调用时,我无法让模型中的 var 被识别
控制器类是
class StaffController {
protected $module = "staff";
public function __construct()
{
//include the staff Model
require_once(MODEL_PATH.$this->module.'.php');
}
public function index() {
// we store all the posts in a variable
$staff = Staff::all();
header('Content-Type: application/json');
echo json_encode($staff);
}
而$staff = Staff::all(); 调用模型类,它的$list 变量无法识别:
class Staff {
public $list = array();
public function __construct() {
$this->list = [];
}
public static function all() {
//get all the staff
$temp = [];
$db = Db::getInstance();
$req = $db->query('SELECT * FROM data ORDER BY ParentID ASC');
// we create a list of Post objects from the database results
foreach($req->fetchAll() as $staff) { array_push($temp,$staff);
self::reorderOrg($temp );
return $final;
}
private static function reorderOrg($array, $parent = 0, $depth = 0){
//reorganise org
for($i=0, $ni=count($array); $i < $ni; $i++){
//check if parent ID same as ID
if($array[$i]['parentID'] == $parent){
array_push($this->list ,$array[$i]); //***** no being recognized
self::reorderOrg($array, $array[$i]['id'], $depth+1);
}
}
return true;
}
}
我收到以下错误在不在对象上下文中使用 $this 以及它与模型类中的 array_push 不喜欢 $this->list 有关。如何设置私有变量,使其可以在自己的类函数中使用
【问题讨论】:
-
静态方法中没有“this”上下文。你必须打电话给
self::$list而不是$this->list。