Alex Rivera | Logout

Why PHP has no default constructor?

Asked 2011-10-26T21:20:11.730
16

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?

Edit
Report

1 Answer

4

As we saw with the 5.3.7 disaster, PHP development could need some more stability. Besides that PHP is different in many more ways.

  • Enterprise Backup is not in the same league (no Oracle, no IBM, etc.)
  • PHP is old, and sometimes inconsistent
  • PHP's Interpreter (Zend Engine) has to be able to do awfully lot, by supporting so many legacy constructs and programming paradigms.
  • PHP's origin is a simple script language for hobbyists.

I really like PHP and work with it daily, but sometimes it's just a little quirk. On the other hand, if you remove __construct() there are two things you should consider.

  1. Never do it, just empty the constructor
  2. If you are building a framework make init functions a core concept since these are even good practice.

I mean this:

class BaseClass {
  public function __construct() {
      if(method_exists($this, 'init') {
          $this->init();
      }
  }
}
answered 2011-10-26T21:40:21.597

Your Answer