PHP Variables, classes and inheritance understanding the basics

I am working on a PHP project and I need some help with the basics. I have a Vehicle class. Within the vehicle class there is a variable called fuel_capacity. As you would expect the fuel capacity changes from vehicle to vehicle. So for example the fuel_capacity changes between a car and a truck. I have a Car class and a Truck class that extend the vehicle class.

On construction of the car I want to assign $fuel_capacity a value. When I do this I can not access $fuel_capacity from the functions within vehicle unless I declare $fuel_capacity public. The problem is if I declare $fuel_capacity public in the Car class then I am worried it will conflict with the $fuel_capacity for the Truck class. Is this correct? If so how do I share the $fuel_capacity with the parent?

Also I want to use a constructor class in my Car class then this overrides my Vehicle class constructor. Is there anyway that I can call for example assign a value such as $fuel_capacity within the Car class and then use that value within the constructor of the Vehicle class?

Finally is there a way to setup an interface for a class that extends from another class?

I have looked at many pages including What's the difference between using normal functions and class methods in PHP?, Understanding inheritance in php, Understanding PHP Inheritance, and What's the difference between using normal functions and class methods in PHP?. These have all been great introduction but they don't address these questions. Thanks :-)


You need to really understand how OOP works and how it is implemented in PHP. http://php.net/oop should be able to help.

Here's one way to do it. You can of course set the fuel capacity in constructor. I recommend Vehicle to be an abstract class since you don't want someone to create a Vehicle object.

If you inherit of course you can access the variable from Car/Trunk classes since its declared protected.

abstract class Vehicle {
    public function setFuelCapacity($capacity) {
        $this->fuel_capacity = $capacity;
    }

    protected $fuel_capacity;
}

class Car extends Vehicle {
}

class Truck extends Vehicle {
}

Hope that helps.

链接地址: http://www.djcxy.com/p/57938.html

上一篇: 我如何使用在PHP中作为类成员存储的回调函数?

下一篇: PHP变量,类和继承了解基础知识