我写了一个类
class User {
private $cars = array(); //store class Car 's object
public function getCars()
{
return $this->cars;
}
public function setCars($cars)
{
$this->cars = $cars;
}
}
class Car{
private $model;
public function getModel()
{
return $this->model;
}
public function setModel($model)
{
$this->model = $model;
}
}
$user = new User();
$cars = $user->getCars();
$cars[0]->getModel();
当我尝试访问getModel()php报告"调用未定义的方法stdClass::getModel()"时。是否有处理此类情况的最佳实践?
编辑:I填满了吸气器和二传手。事实上,它是由phpstorm生成的。
编辑:I再次尝试,它适用于下面的演示代码。原始代码太复杂,无法显示。也许我是由我对按值和数组引用复制的误解引起的。
请忽略这个问题。对不起。
class User {
private $cars = array(); //store class Car 's object
public function getCars()
{
return $this->cars;
}
public function setCars($cars)
{
$this->cars = $cars;
}
}
class Car{
private $model;
public function getModel()
{
return $this->model;
}
public function setModel($model)
{
$this->model = $model;
}
}
$user = new User();
$car = new Car();
$car->setModel("Ford");
$arr = $user->getCars();
array_push($arr,$car);
$user->setCars($arr);
foreach($user->getCars() as $car) {
var_dump($car->getModel());
}
您尚未显示[Getter Setter ]
代码。您需要创建一个类似以下内容的内容:
public function setCars($val){
$this->cars = $val;
}
public function getCars(){
return $this->cars;
}
这同样适用于getModel()