Why PHP has no default constructor?

paq85 picture paq85 · Oct 26, 2011 · Viewed 8.7k times · Source

Why can't I use code like this?

<?php

class NoConstructor {
}

class ChildWithConstructor extends NoConstructor {
    public function __construct() {
        parent::__construct();
        // do something
    }
}

$foo = new ChildWithConstructor();
// **Fatal error: Cannot call constructor in file.php on line 8**

Eg. Java classes have default, no args constructor. It can be called even if it's not explicitly defined.

PHP behavior can cause troubles when we remove no args constructor from parent class, eg. when we think it's not needed any more.

Does anyone know why PHP creators made it this way?

Answer

Boann picture Boann · Oct 26, 2011

Java classes have default, no args constructor.

Does anyone know why PHP creators made it this way?

Java was a planned language. It was rigorously considered and formally specified from the get-go. It was intended to last as long as possible with minimal changes for sake of backwards and forwards compatibility, for simplicity to developers and implementers alike. The definitely didn't succeed to the degree they hoped, but you can still take Java 1.0 code, compile it and run it on modern VMs.

PHP's designers never planned the language to nearly such an extreme. They make it up as they go along. For better or worse, they're moderately willing to throw the language apart and rebuild it in the next version. It's changed unrecognizably since PHP 1 and 2. Even recently, in PHP 5, you had the dramatic change from by-value to by-reference semantics for objects. It's that same brilliant methodology that brought us magic quotes, the lack of Unicode, inconsistently named (and frequently renamed) functions, and a parser that without even a hint of error (even with error_reporting(-1);), will merrily interpret the numeric literal 09 as 0.

PHP behavior can cause troubles when we remove no args constructor from parent class, eg. when we think it's not needed any more.

You could request this be changed on bugs.php.net, but chances are they'll ignore it or fob you off with "Sorry, but your issue does not imply a problem in PHP itself...".