[thelist] OO PHP call a method on class when instantiated

Burhan Khalid thelist at meidomus.com
Wed Jun 15 05:54:57 CDT 2005

Simon Perry wrote:
> Hi,
> I would like to call a method of my class when an instance of the class 
> is instantiated but I'm at a loss as to how to do this. I have googled 
> without joy. The method populates various vars that will always be 
> required. At the moment I create an instance and then call the method  
> but that seem inefficient. I'm sure I'm missing something very simple 
> here...

You need a constructor.  This is a special function that is called when 
an object of a class is created.

In PHP 4, a constructor is simply a method in a class with the same name 
as the class itself :

class hello { var $i = null; function hello() { $thi->i = 1; } }

$obj = new hello();
echo $obj->i; // Will ouput 1

In PHP 5, you have to use a special method called __construct

class hello { function __construct() { echo 'hello'; } }

$obj = new hello(); // will print 'hello'

Not that unlike some other OOP languages, you cannot have overloaded 
constructors in PHP.

More information about the thelist mailing list