doug Posted June 2, 2008 Share Posted June 2, 2008 I've been going through the O'Reilly book "Programming PHP". In the section on object constructors, there seems to be a mistake and I wanted to get your opinions of it. The section says: A constructor is a function in the class called __construct(). Here’s aconstructor for the Person class: class Person { function __construct($name, $ag‘e) { $this->name = $name; $this->age = $age; } } PHP does not provide for an automatic chain of constructors; that is, if you instanti- ate an object of a derived class, only the constructor in the derived class i sautomati- cally called. For the constructor of the parent class to be called, the constructor in the derived class must explicitly call the constructor. In this example, the Employee class constructor calls the Person constructor: class Person { var $name, $address, $age; function Person($name, $address, $age) { $this->name = $name; $this->address = $address; $this->age = $age; } } class Employee extends Person { var $position, $salary; function Employee($name, $address, $age, $position, $salary) { $this->Person($name, $address, $age); $this->position = $position; $this->salary = $salary; } } But in the example, a function __construct() is nowhere to be found. Is this an error, or can a function the same name as the class itself be used instead of the function name __construct?Thanks,doug Link to comment Share on other sites More sharing options...
Fukushousha Posted June 2, 2008 Share Posted June 2, 2008 Yep , in all other languages a constructor is a public function of the name itself. So PHP uses it too just to be like every other cool kid(language) in the block :)I am no expert but I think it is preferred to use __construct() in php though. Link to comment Share on other sites More sharing options...
justsomeguy Posted June 3, 2008 Share Posted June 3, 2008 In PHP4 the classes used a constructor with the same name as the class, as some other languages do. In PHP5 the reserved name __construct is used for the constructor. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.