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 )

PHP code to write to a CSV file from MySQL query

Different versions of PHP - History and evolution of PHP

PHP code to import from CSV file to MySQL

Send push notifications using Expo tokens in PHP

A Basic Example using PHP in AWS (Amazon Web Services)

Encrypting files using GnuPG (GPG) via PHP

PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......

Decrypting files using GnuPG (GPG) via PHP

Parent: child process exited with status 3221225477 -- Restarting

Error: Length parameter must be greater than 0

Convert a hex string into a 32-bit IEEE 754 float number in PHP

Password must include both numeric and alphabetic characters - Magento

Convert XML to CSV in PHP

PHP file upload prompts authentication for anonymous users

Reading word by word from a file in PHP

Latest Articles (in PHP)