ÄúµÄλÖãºÑ°ÃÎÍøÊ×Ò³£¾±à³ÌÀÖÔ°£¾PHP ±à³Ì£¾PHP 5 Power programming
Team LiB
Previous Section Next Section

3.4. The new Keyword and Constructors

Instances of classes are created using the new keyword. In the previous example, we created a new instance of the Person class using $judy = new Person();. What happens during the new call is that a new object is allocated with its own copies of the properties defined in the class you requested, and then the constructor of the object is called in case one was defined. The constructor is a method named __construct(), which is automatically called by the new keyword after creating the object. It is usually used to automatically perform various initializations such as property initializations. Constructors can also accept arguments, in which case, when the new statement is written, you also need to send the constructor the function parameters in between the parentheses.

In PHP 4, instead of using __construct() as the constructor's name, you had to define a method with the classes' names, like C++. This still works with PHP 5, but you should use the new unified constructor naming convention for new applications.

We could have rewritten the previous example to pass the names of the people on the new line:

class Person {
    function __construct($name)
    {
        $this->name = $name;
    }

    function getName()
    {
        return $this->name;
    }

    private $name;
};

$judy = new Person("Judy") . "\n";
$joe = new Person("Joe") . "\n";

print $judy->getName();
print $joe->getName();

This code has the same result as the previous example.

Tip

Because a constructor cannot return a value, the most common practice for raising an error from within the constructor is by throwing an exception.


    Team LiB
    Previous Section Next Section