I have stated my bespoke MV, I have a simple Model + controller classes and I can't get the var in the model to be recognsed when called by a different function
The controller class is
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);
}
And $staff = Staff::all();
calls the model class, and its the $list
variable that isn't recognized:
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;
}
}
I get the following error Using $this when not in object context in and its to do with the array_push in the model class not liking $this->list
. How do a set the private var so it can be used within its own class funcitons
The static
keyword means that that function is called on the class itself, not on an instance of the class. That means $this
doesn't refer to anything.
If it's a function that needs to be called on a specific instance so that you have access to its members, you'll need to either make it non-static or pass in an instance of the class (probably the former, since that's what a non-static method is for).
As far as having the class keep a list of its instances: What you're doing here is initializing a list
on an instance of your class, so each instance will have an empty list. This may not be what you're intending.