The new keyword and constructors in PHP

By: Andi, Stig and Derick  

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.




Archived Comments


Most Viewed Articles (in PHP )

Iterating Through an Array in PHP

unset() and empty() functions in PHP

PHP pages does not display in IIS 6 with Windows 2003

Warning: session_start(): open .... failed - PHP error

PHP ./configure RESULTING IN [email protected]_2_2_3_... AND UNRESOLVED REFERENCES WITH ORACLE OCI8

PHP 5.1.4 INSTALLATION on Solaris 9 (Sparc)

Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

Installing PHP 5.x with Apache 2.x on HP UX 11i and configuring PHP 5.x with Oracle 9i

Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Function to return number of digits of an integer in PHP

Function to force strict boolean values in PHP

Function to sort array by elements and count of element in PHP

Latest Articles (in PHP)

Comment on this tutorial