A few days ago I saw an interview question:
<?phpclass parentclass { function __construct () { $this->hello (); } Public function Hello () { echo __class__. ' /'. __function__; }} Class ChildClass extends ParentClass {public function Hello () { echo __class__. /'. __function__; }} New ChildClass ();? >
Ask the result of the final output:
1, __construct () as the constructor of the class, called when the class is instantiated
2, if the parent class has a display call __construct (), The subclass is not called, then the subclass uses the parent Class's __construct () initialization, and the call is subject to the private, that is, if the parent class __construct () is Private decorated, And the subclass does not explicitly call its own __construct (), that will be an error, the subclass does not have permission to call the parent class private __construct ()
3, the Kawai class has the display call __construct (), then calls the parent class __construct needs to display the declaration, namely Parent::__construct ()
4, $this represents the current object, self:: represents the current class itself
5, php Default method is public, member variable is private
From this we can conclude that:
New ChildClass ();
ChildClass calls the constructor of parentclass, which is the Hello () method of the current object, outputs the class name of the class to which this object belongs and the name of this method, and the class that owns the object is naturally childclass, so the result is:
Childclass/hello
Process:
New ChildClass () first checks whether it has a parent class, whether it has an explicit call to its own constructor, if it has a constructor, then, if there is no parent class, the constructor of the parent class is called (the constructor is also modified by public private, note).
It is not necessary to understand that in order to construct itself in a parent class, it can be understood that the constructor of the parent class is copied to its own memory unit for use
Its own constructor inherits the parent class by Default.
$this->hello ();
Call your own Hello () method, and the output can Be.
If you have a constructor, the parent class is overridden, calling the constructor of the parent class:
<?phpclass parentclass { function __construct () { $this->hello (); } Public function Hello () { echo __class__. ' /'. __function__; }} Class ChildClass extends ParentClass { //if not written, Use the function of the parent class __construct () { parent::__construct (); } Public function Hello () { echo __class__. ' /'. __function__; }} New ChildClass ();? >
If you want this class to no longer be inherited, you can use the final decoration
Final class ClassName {//cannot be inherited by entends}
PHP on the inheritance and invocation of __construct ()