警告:在第16行的空值中创建默认对象

时间:2018-04-22 22:20:14

标签: php

我在我的PHP代码中出现错误"警告:在"中从空值创建默认对象代码如下:

class carshop
{
    public $cars = array();
    public $car_brand,$car_name, $car_modal,$car_price;

    public function set_cars($car_brand,$car_name,$car_modal,$car_price)
    {

        $n_cars = count($this->cars);
错误行上的

从这里开始:

        $this->cars[$n_cars]->car_brand = $car_brand;
        $this->cars[$n_cars]->car_name = $car_name;
        $this->cars[$n_cars]->car_modal = $car_modal;
        $this->cars[$n_cars]->car_price = $car_price;
    }



    public function print_cars()
    {
        echo "<b>Car Stock: </b> We Have " 
        .count($this->cars). " Cars Infromation ! </br></br>";
        for ($i=0; $i < count($this->cars) ; $i++) { 
            echo "<b><u>Car No: ".$i."</u></b> " 
            .$this->cars[$i]->car_brand. " ,"
             .$this->cars[$i]->car_name. " ,"
              .$this->cars[$i]->car_modal. " , \$"
               .$this->cars[$i]->car_price;
            echo "</br>";
        }
    }
}
对象从这里开始:

$shop = new carshop();
$shop->set_cars("Honda","Civic","2017",2400000);
$shop->set_cars("Honda","City","2012",1200000);
$shop->set_cars("Honda","Accord","2015",1100000);
$shop->print_cars();

1 个答案:

答案 0 :(得分:0)

$cars类的

carshop字段作为数组:

public $cars = array();

从代码中,我认为你打算将它作为一系列汽车。发生错误是因为您这样做:

$this->cars[$n_cars]->car_brand = $car_brand;

$this->cars[$n_cars]的值为null

也许你可以分开你的班级 - 一个来处理汽车商店的商业逻辑,另一个代表一辆汽车。如下:

class Car
{
    public $car_brand, $car_name, $car_modal, $car_price;
}

class CarShop
{
    public $cars = array();

    public function set_cars($car_brand,$car_name,$car_modal,$car_price)
    {
        $n_cars = count($this->cars);
        $this->cars[$n_cars] = new Car();  // <-- Create a new Car object and add it to the cars array
        $this->cars[$n_cars]->car_brand = $car_brand;
        $this->cars[$n_cars]->car_name = $car_name;
        $this->cars[$n_cars]->car_modal = $car_modal;
        $this->cars[$n_cars]->car_price = $car_price;
    }

    // ... Rest of your CarShop class here
}