tags:

views:

191

answers:

3

I want code to run whenever I create a new object. For example, see this:

<?php

class Test {
echo 'Hello, World!';
}

$test = new Test;

?>

I want it to echo "Hello, World!" whenever I create a new instance of this object, without calling a function afterward. Is this possible?

+6  A: 
class Test {
 function __construct(){
    echo 'Hello, World!';
 }
}
Trey
Worth mentioning: this is PHP5+ way.. Shouldn't matter but still..
dr Hannibal Lecter
To be fair, PHP4 is largely obsolete now.
Turnor
+8  A: 

You should read about constructor

Luc M
+1  A: 

Or on PHP 4 use:

class Test {
    function Test {
        echo 'Hi';
    }
}

Edit: This also works on PHP 5, so this is the best way to do it.

Henri Watson
I think __construct() is the better way, because it doesn't work in PHP4. :-)
Craig Lewis