Home >Backend Development >PHP Tutorial >PHP constructor method calling problem when creating class instance_PHP tutorial

PHP constructor method calling problem when creating class instance_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 14:54:271035browse

This article talks about the problem of calling the constructor method when PHP creates an instance of a class.

Unlike Java in PHP, when creating an instance of a class, the constructor of the parent class (super class) will be automatically called first to ensure that all attributes can be initialized correctly. PHP will not automatically call the constructor of the parent class in the constructor of this class. If you really need to call the parent class's constructor, you can manually call parent::__construct($params...);

class Base{
function __construct(){
//do sth here....
}
}

If we need an Extender to inherit Base, what we need to pay attention to is

1. Do we need to call the parent class? The constructor is used for initialization

2. Do we need to perform other extension operations based on the parent class constructor?

3. We do not need the initialization actions in the Base constructor .

If our Extender only satisfies situation 1, then we can omit the Extender's constructor, because the parent class's constructor fully meets our requirements, and we do not need to perform additional coding.

If our Extender satisfies situation 2, then we must first call parent::__construct() in the Extender's constructor, initialize it first, and then perform some extension operations

If our Extender satisfies In case 3, we can choose not to call the constructor of the parent class. There is just one flaw in this: when we expand Extender, if the extended class requires the initialization operation of the Base constructor, calling parent::__construct() at this time can only call the constructor of Extender but not the constructor of the Base class. Method.

Therefore, I personally think that it is better to manually call the constructor of the parent class in the constructor of the subclass.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/364611.htmlTechArticleThis article talks about the problem of calling the constructor method when PHP creates an instance of a class. In PHP, unlike Java, when creating an instance of a class, the parent class (super...
will be automatically called first)
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn