PHP类数组对象方法访问问题
我写了一节课PHP类数组对象方法访问问题,php,oop,Php,Oop,我写了一节课 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{ p
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()”时。
是否有处理此类案件的最佳做法
编辑:我填写了getter和setter。事实上,它是由phpstorm生成的
编辑:我再试了一次,它与下面的演示代码配合得很好。原始代码太复杂,无法显示。可能是因为我误解了按值复制和按数组引用复制
请忽略这个问题。对不起
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()
显示您的完整代码,在您的代码中没有getCars
或getModel
方法?请显示真实代码,您没有显示为User::cars
设置的内容。根据错误消息,它不是Car
对象,因此在设置属性时,代码中可能存在错误。但如果没有真正的代码,我们只能猜测。