PHP创建对象数组get方法失效、属性赋值异常问题求助
核心错误点
- 类属性访问语法错误:PHP中访问类内部定义的属性,语法为
$this->属性名,属性名前不需要加$符号。你代码中所有$this->$id、$this->$weight这类写法都是错误的,相当于把变量$id的值作为动态属性名赋值,因此会出现大量以传入参数值为键名的异常属性,原有声明的私有属性没有被正确赋值,调用getId()时会因为找不到对应变量抛出警告。 global关键字误用:你已经在ItemModel类中声明了私有属性private $item = array(),要访问该属性需要用$this->item,global声明的是全局作用域下的$item变量,和类属性完全无关,因此会出现不加global就无法访问的问题。- 方法名拼写错误:
Car类中获取model的方法名误写为getmMdel,多了一个冗余的m字符。
修正后的代码
ItemModel类
class ItemModel{ private $item = []; public function setItems(){ $test = new Bmw("test....", "BMW", 32, 1, 120); $this->item[] = $test; } public function getItems(){ return $this->item; } }
Car抽象类
abstract class Car{ private $id; private $model; private $price; private $carTypeId; public function __construct($id, $model, $price, $carTypeId){ $this->id = $id; $this->model = $model; $this->price = $price; $this->carTypeId = $carTypeId; } public abstract function getAdditionalInfo(); public function getId(){ return $this->id; } public function getModel(){ return $this->model; } }
Bmw类
class Bmw extends Car{ private $weight; public function __construct($id, $model, $price, $carTypeId, $weight) { parent::__construct($id, $model, $price, $carTypeId); $this->weight = $weight; } public function getAdditionalInfo(){ return "Weight: ".$this->weight; } }
ItemView类
class ItemView extends ItemModel{ public function showItems(){ $this->setItems(); foreach ($this->getItems() as $item) { print_r($item->getId()); } die; } } $test = new ItemView(); $test->showItems();
修正后代码运行将正常输出test....,不会抛出警告,对象属性赋值也会全部正常。
内容的提问来源于stack exchange,提问作者Jānis Kļaviņš
相关产品推荐
相关产品推荐

