Amit Shah

An IT Professional

Home
Object Oriented Programming in PHP - Constructors PDF Print E-mail
User Rating: / 2
PoorBest 
You might define constructors in your classes; constructors are methods with the same name as the class and are called when you create an object of the class, for example: <?php

class Something {
var $x;

function Something($y) {
$this->x=$y;
}

function setX($v) {
$this->x=$v;
}

function getX() {
return $this->x;
}
}

?>

So you can create an object using:

$obj=new Something(6);

...and the constructor automatically assigns 6 to the data member x.

Constructors and methods are normal PHP functions so you can use default arguments.

function Something($x="3",$y="5");

Then:

$obj=new Something(); // x=3 and y=5
$obj=new Something(8); // x=8 and y=5
$obj=new Something(8,9); // x=8 and y=9

Default arguments are used in the C++ way so you can't pass a value to Y and let X take the default value. Arguments are assigned from left to right and when no more arguments are found if the function expected more they take the default values.

When an object of a derived class is created only its constructor is called the constructor of the Parent class is not called.

This is a gotcha of PHP because constructor chaining is a classic feature of OOP, if you want to call the base class constructor you have to do it explicitly from the derived class constructor.

It works because all methods of the parent class are available at the derived class due to inheritance.

<?php

function Another() {
$this->y=5;
$this->Something(); //explicit call to base class constructor.
}

?>

Abstract Classes

A nice mechanism in OOP is the use of Abstract Classes; abstract classes are classes that cannot be instantiated and the only purpose is to define an interface for its derived classes.

Designers often use Abstract classes to force programmers to derive classes from certain base classes, so they can be certain that the new classes have some desired functionality.

There's no standard way to do that in PHP but, if you do need this feature, just define the base class and put a "die" call in its constructor so you can be sure that the base class is never instantiated.

Now define the methods (interface) putting "die" statements in each one so if in a derived class a programmer doesn't override the method then an error is raised.

Furthermore you might need to be sure, since PHP has no types, that some object is from a class derived from your base class, then add a method in the base class to identify the class (return "some id") and verify this when you receive an object as an argument.

Of course this doesn't work if the evil programmer overrides the method in the derived class but generally the problem is dealing with lazy programmers not evil ones! Of course it’s better to keep the base class unreachable from the programmers, just print the interface and make them work!

There're no destructors in PHP.
 
< Prev   Next >

Tag Here