Constructor (object-oriented Programming) - PHP

PHP

In PHP (version 5 and above), the constructor is a method named __construct, which the keyword new automatically calls 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.

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

However, constructor in PHP version 4 (and earlier) is a method in a class with the same name of the class. In PHP 5 for reasons of backwards compatibility with PHP 4, when method called __construct is not found, a method with the same name as the class will be called instead. Since PHP 5.3.3 this fallback mechanism will only work for non-namespaced classes.

class Person { private $name; function Person($name) { $this->name = $name; } function getName { return $this->name; } }

Read more about this topic:  Constructor (object-oriented Programming)