PHP从扩展类/父母类添加属性

问题描述

我有一个项目,我尝试将父类(vehicle.php)的属性实现为landvehicle.php。所有属性都设置为public。我的目标是在这种特殊情况下,将Vehicle for Landvehicle的属性用于$ landOne($ height)。

Vehicle.php:

<?php

class Vehicle
{
    public $length;
    public $height;
    public $color;
    public $weight;
    public $price;
    public $range;


    public function __construct($length,$height,$color,$weight,$price,$range)
    {
        $this->length = $length;
        $this->height = $height;
        $this->color = $color;
        $this->weight = $weight;
        $this->price = $price;
        $this->range = $range;
    }
    public function addHeight()
    {
        return "$this->height is the height";
    }


}

$userVehicleOne = new Vehicle('2.5 Meter','1,3 Meter','red','1800kg','40.000€','450km');

Landvehicle.php:

<?php

include 'vehicle.php';

class Landvehicle extends Vehicle
{
    public $amountWheels;
    public $movementType;

    public function __construct($amountWheels,$movementType)
    {
        $this->amountWheels = $amountWheels;
        $this->movementType = $movementType;
    }

}

$landOne = new Landvehicle ('4','flexible');



echo $landOne->addHeight('1.50Meter')

我尝试使用Vehicle.php中的addHeight函数将$ landOne的高度设置为1.50米

解决方法

在addHeight方法中,您不接受任何参数;在Landvehicle.php中,您将1.50Meter用作第一个参数,这是不正确的。删除您的addHeight方法,并将其替换为以下代码:

public function addHeight($height)
{
    $this->height = $height;
    return "$this->height is the height";
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...