free tutorials logo spacer
spacer
PHP
 
     
   
shaddow bottom left

4- Constructors, Extending the vehicle example 1

A useful feature of object oriented PHP is the ability to make a class do something as soon as it comes to life, particularly, you would probably want a method (function) to fire up as soon as you instantiate the object, and you would probably prefer that you can have some control on what happens when that method is executed.

Fortunately, we have the __construct method, Just put a method with the name __construct (Notice the double underscore) put it in a class, and every time we instantiate an object of that class, the __construct method will execute, But what about control ?

Let us remake the vehicle class with a constructor method, all we are doing here is adding the __construct method to the vhicle class.

class vehicle
{
public $price = "25000";
public $manufacturer = "Toyota"; public $engineSize = "2 Liter"; public $color = "White";
function getspecs() { return "Vhicle Manufacturer: {$this->manufacturer} \n<br> Engine Size: {$this->engineSize} \n<br> Color: {$this->color}\n<br> Price: {$this->price} "; } function __construct($price, $manufacturer, $engine, $color) { $this->price = $price; $this->manufacturer = $manufacturer; $this->engineSize = $engine; $this->color = $color; }
}


You can control the construct method by passing arguments, just like you would call a normal function, we simply instantiate the object like this

$accord = new vehicle(30500, "Honda", "2.5 Liter", "Red");

So, what happened here is that the class passed all the parameters passed to it down to the constructor, and the constructor then set all the properties inside that object to the values it received in the argument list, So if we now run

print $accord->getspecs();

This will display

Vhicle Manufacturer: Honda
Engine Size: 2.5 Liter
Color: Red
Price: 30500

to our browser

We will come back to constructors again soon (For inheritance, and for other parts), for now, it does the trick fine.

It is worth mentioning that methods are sometimes and in some casses classified to either getters or setters, methods that get data from within an Object are getters, those that set the values in an object are setters, but as you can imagine, this is just naming of methods, A method is a function, and it can do anything or a combination of things.

NEXT: 05-Inheritance-Extending-the-vehicle-example-2.html


Your Name:

Subject:

Your Comment: