Execute code when instantiating PHP class?

I want the 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 the function after that. Is it possible?

+1


a source to share


3 answers


You should read the constructor



<?php
class MyClass {
   public function __construct() {
      echo "This code is executed when class in instanciated.";
   }
}
?>

      

+8


a source


class Test {
 function __construct(){
    echo 'Hello, World!';
 }
}

      



+6


a source


Or in 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.

+2


a source







All Articles