【发布时间】:2021-09-04 02:56:06
【问题描述】:
我正在尝试创建一个对象数组,但有几个问题。
- 首先我不能在 ItemModel 类函数中使用 $item= array() 而不使其成为全局函数。
- 其次,我得到了一些奇怪值的数组。
我是编程新手,谁能解释一下我做错了什么?
class ItemModel{
private $item= array();
public function setItems(){
global $item;
$test = new Bmw("test....", "BMW", 32, 1, 120);
$item[] = $test;
}
public function getItems(){
global $item;
return $item;
}
}
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 getmMdel(){
return $this->$model;
}
}
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;
}
}
class ItemView extends ItemModel{
public function showItems(){
$this->setItems();
foreach ($this->getItems() as $item) {
print_r($item);
}
die;
}
}
$test = new ItemView();
$test->showItems();
Results:
Bmw Object
(
[weight:Bmw:private] =>
[id:Car:private] =>
[model:Car:private] =>
[price:Car:private] =>
[carTypeId:Car:private] =>
[test....] => test....
[BMW] => BMW
[32] => 32
[1] => 1
[120] => 120
)
当我尝试通过更改来使用函数 getId() 时
foreach ($this->getItems() as $item) {
print_r($item->getId());
}
我明白了
PHP Warning: Undefined variable $id in /workspace/Main.php on line 43
PHP Warning: Undefined property: Bmw::$ in /workspace/Main.php on line 43
【问题讨论】:
-
$this->item应该可以工作 -
在引用例如时从所有类属性中删除
$符号$this->$id= $id;=>$this->id= $id; -
感谢 Alberto Sinigaglia 和 B001ᛦ。通过删除 $ 修复了该问题
标签: php arrays class object constructor