views:

53

answers:

4

So I am getting started with OO PHP, and after reviewing a variety of classes which I have downloaded from the internet, I have noticed that some - but not all of these classes have an intial function with the same name e.g.

class MyClass{

function MyClass{

//function contents in here

}

function otherfunction{

//more stuff here

}

}

what is this inital function for? and how does it help with writing classes?

+5  A: 

It's an old-style constructor. If you are using PHP 5 (you ought to), you should avoid those constructors and do instead:

class MyClass{

    function __construct() {
        //function contents in here
    }

    function otherfunction() {
        //more stuff here
    }
}

Constructors are, in short, used to run initialization code and enforce class invariants.

Artefacto
The old C++-style constructors are less photosensing. But apart from that, is there also any functional difference to the Python-style constructors?
mario
@mario: No, both styles are functionally equivalent.
Piskvor
A: 

it is a constructor - anything put in here is executed when the object is instantiated

Robert
A: 

That function is a constructor. It is used for initializing the object.

Constructor

msergeant
A: 

please also note that it's case insensitive. For example whan you have a Bark() class for a dog game the class name Bark is your reference to the noise that a dog makes.

If you want a specifig dog (e.g. a poodle which extends a general Dog pbject) to bark, you could name that method bark(), because that's what you want the dog to do (see the duality between the THING and the COMMAND ? (Bark class and bark() method) ).

So, when you do this:

interface BarkBehaviour { public function bark(); }

class Bark implements BarkBehaviour { public function bark() { echo "\nWoof!"; } }

the instantiation of the barkBehaviour property of your dog will echo "Woof", because PHP thinks that the bark() method is the constructor for the Bark class, which you did NOT intend that way. In JAVA these things are case sensitive so the Bark classes constructor must be called Bark(), not bark().

marvelade