Friday, December 22, 2006

Constructor in PHP

Some modules will not be able to run on Cube Legacy 2.1. One of causes is that a sub class's constructor hides its base class's constructor. Mr, Marijuana pointed this problem. But, I think that developers who have written such code might not have intended to hide it. In other words, they didn't have known a certain spec of PHP.

class A
{
 var $mFuncB;

 function A()
 {
  $this->mFuncB =& new XCube_Delegate();
 }

 function funcB()
 {
  $this->mFuncB->call();
 }
}

class B extends A
{
 var $mFlag;

 function B()
 {
  $this->mFlag =& new Flag();
 }
}

$instance =& new B();
$instance->funcB();

Most developers don't find any problems in the upper program. But, the program raises fatal error, when funcB() is called. It's the cause that mFuncB is not initialized. In fact, base class's constructor is not passed automatically in PHP language, unlike other common program languages. I had fallen into this problem many times.

When you write constructor, you must call base's constructor expressly using parent keyword.

class B extends A
{
 function B()
 {
  parent::A();
 }
}

That's strange code! But if you don't have specific initialization code in your sub class, you may omit the constructor. Because empty constructor must has parent call, this spec is very useful. I often omit the constructor.

In XOOPS Cube Legacy 2.1, some classes got to have additional initialization code in their constructor. Therefore, in the case where a sub class hide base class's constructor, it may be the cause of imcompatibility issues. Developers need to notice difference between the spec of PHP and other common language.

Base class's constructor should not be hidden, even if it's possible to do it in PHP. Therefore, XOOPS Cube coding rule will make reference to this problem for module developers.

  • In PHP, you don't exactly need to write the constructor like C++ and more.

  • If you must write the constructor, insert parent calls to the first part of the constructor to suit other languages.

I don't know professional web programing. But, hiding constructor might not be common tips for PHP programmers. It's denying of inheritance that a sub class's constructor hides its base class's constructor.

2 comments:

Anonymous said...

Hey Minahito, thanks a lot for this post. I was trying to call the base class constructor and thought it would normally pass. Thanks a lot for this eye-opener post.

Anonymous said...

thanks for your post. solved my problem :)