Php 不在对象上下文模型类中时使用$this
我已经说明了我的定制MV,我有一个简单的模型+控制器类,当由不同的函数调用时,我无法使模型中的var重新编码 控制器类是Php 不在对象上下文模型类中时使用$this,php,class,protected,Php,Class,Protected,我已经说明了我的定制MV,我有一个简单的模型+控制器类,当由不同的函数调用时,我无法使模型中的var重新编码 控制器类是 class StaffController { protected $module = "staff"; public function __construct() { //include the staff Model require_once(MODEL_PATH.$this->module.'.php
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得到以下错误,这与模型类中的数组\u push不喜欢$this->list有关。如何设置私有变量,使其可以在自己的类函数中使用您不在对象上下文中,因为您的函数是静态的。你必须改用self。self指的是当前类:
array_push(self::list, $array[$i]);
static关键字意味着该函数是在类本身上调用的,而不是在类的实例上调用的。这意味着$this不指任何东西
如果它是一个需要在特定实例上调用的函数,以便您能够访问其成员,那么您需要使其成为非静态的,或者传入类的实例(可能是前者),因为这就是非静态方法的用途
至于让类保留其实例的列表:您在这里所做的是初始化类实例的列表,因此每个实例都有一个空列表。这可能不是您想要的。您不能在静态方法中使用$This,因为静态方法不是$This引用的实例化对象的一部分。即使对象未实例化,也可以调用静态方法
您必须使reorderOrg非静态才能工作。请阅读PHP中的静态方法和属性 您不能在静态方法中访问$this,因为您没有任何应称为$this的类实例 你有两个选择 将属性声明为静态并使用self关键字访问它。比如说 //声明 公共静态$list=数组 //通路 self::$list[]=“某物” 创建类的对象并访问所创建对象的属性 //创建对象 $staff=新员工 //通路 $staff->list[]=“某物” 记住要读这本书 相关职位: 这能回答你的问题吗?使用静态方法时;您必须使用self::not$this->
在静态方法中没有此上下文的上下文。您必须调用self::$list,而不是$this->list。
array_push(self::list,...);