我已经说明了我的定制MV,我有一个简单的Model+控制器类,当被不同的函数调用时,我无法重新配置模型中的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
有关。如何设置私有var,使其可以在自己的类函数
static
关键字意味着该函数是在类本身上调用的,而不是在类的实例上调用的。这意味着$this
没有提及任何内容。
如果它是一个需要在特定实例上调用的函数,以便您可以访问其成员,那么您需要使其成为非静态的,或者传入类的实例(可能是前者,因为这就是非静态方法的作用)。
至于让类保留其实例的列表:您在这里所做的是在类的实例上初始化list
,因此每个实例都有一个空列表。这可能不是你想要的。
您不在对象上下文中,因为您的函数是静态。您必须使用self
。self
表示当前类别:
array_push(self::list, $array[$i]);
您不能在静态方法中使用$this
,因为静态方法不是$this
引用的实例化对象的一部分。即使对象没有实例化,也可以调用静态方法。
为了工作,您必须使reorderOrg
非静态。
请阅读PHP中的静态方法和属性。
您不能在静态方法中访问$this
,因为您没有任何应称为$this
的类实例。
这里有两个选项
将属性声明为static,并使用
self
关键字对其进行访问。例如//申报
public static$list=array();
//访问
self::$list[]='something';
创建类的对象并访问所创建对象的属性。
//创建对象
$staff=新员工();
//访问
$staff->list[]='something';
记得阅读文档!
相关文章:在静态函数中使用此函数会使失败
这能回答你的问题吗?当使用静态方法时;您必须使用self::而不是$this->
http://php.net/manual/en/language.oop5.static.php
array_push(self::list,...);