w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Calling parent constructor within child class

If the iParentChild class does not define __construct then it inherits the one from it's superclass, iParent. If it did define __construct then that would override the parent's constructor and hence, as stated in your question, would need to call parent::__construct().


Note that even if iParentChild does override __construct without calling the parent constructor there will not be an error in this example. This is because php provides default initialisation of variables in the context in which they are used and here they are used as strings. In practice it is best not to rely on this:

From the PHP Manual - Basics:

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.

An attempt to call a method on an uninitialised member object would have resulted in an error.

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.