【问题标题】:Warning: Creating default object from empty value in on line 16警告:在第 16 行从空值创建默认对象
【发布时间】:2018-04-22 22:20:14
【问题描述】:

我的 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();

【问题讨论】:

  • $this-&gt;carsarray 而不是 object。你应该这样做:$this-&gt;cars[$n_cars]['car_brand'] = $car_brand;

标签: php


【解决方案1】:

carshop 类的$cars 字段作为数组:

public $cars = array();

从代码中,我推测您打算将其作为一组汽车。发生错误是因为您正在这样做:

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

但是$this-&gt;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
}

【讨论】:

    猜你喜欢
    • 2021-08-15
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    相关资源
    最近更新 更多