Start PHP Code RESULT
Hello! My name is Bob
Hello! My name is Harry
Hello! My name is anon
End PHP Code RESULT
The PHP Code START
class first_class {
    var $name;
    function first_class( $n = "anon" ) {
        $this->name = $n;
    }
    function sayHello() {
        print "Hello! My name is $this->name<br />";
    }
}

$obj1 = new first_class("Bob");
$obj2 = new first_class("Harry");
$obj3 = new first_class();
$obj1->sayHello();   // Outputs "Hello! My name is Bob"
$obj2->sayHello();   // Outputs "Hello! My name is Harry"
$obj3->sayHello();   // Outputs "Hello! My name is anon"

The PHP Code END

 

If you create a method with exactly the same name as the class, it will automatically be called when a new object is instantiated. In this way, you can give your objects arguments to process at the moment you instantiate them (moment of "birth").

Objects can run code to initialize themselves based on these arguments or other factors.

These special methods are called constructors. This program (listing 8.3) adds a constructor to the first_class class (pg 124 Sama 24 Hour PHP)