Programming Tutorials

The new keyword and constructors in PHP

By: Andi, Stig and Derick in PHP Tutorials on 2008-11-22  

Instances of classes are created using the new keyword. 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 pass the names of the people on the new line in the following class example :

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();

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.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

Latest Articles (in PHP)