search
Homephp教程php手册php 创建类实例的构造方法调用问题

php 创建类实例的构造方法调用问题

Jun 13, 2016 am 11:36 AM
phpcreateExamplemethodyesofkindtransferquestion

本文说的是php创建一个类的实例的时候,构造方法调用的问题。

php中不像java一样,创建一个class的实例的时候 会自动的首先调用父类(超类)的构造方法,以确保所有的属性都可以被正确的初始化。php 不会在本类的构造方法中再自动的调用父类的构造方法。如果真的需要调用父类的构造方法,可以手动的调用parent::__construct($params...);   

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

如果我们需要些一个Extender 来继承Base,我们需要注意的是

1、我们是否需要调用父类的构造方法用于初始化

2、我们是否需要在父类构造方法的基础上在进行其他的一些扩展操作

3、我们不需要Base构造方法中的那些初始化动作。

如果我们的Extender 只满足情况1,那么我们可以省略Extender的构造方法,因为父类的构造方法完全符合我们的要求,我们就没有必要再进行额外的编码。

如果我们的Extender 满足情况2,那么我们要在 Extender的 构造方法中 先调用parent::__construct(),先进行初始化,然后 在进行一些扩展操作

如果我们的Extender 满足情况3,我们可以选择不调用父类的构造方法。只是这样做有一个缺陷:我们再扩张Extender的时候,如果这个扩展类需要Base构造方法的初始化操作,这时候再调用parent::__construct() 只能调用 Extender的构造方法 而不能调用 Base 类的构造方法.

所以,个人认为,最好还是在子类的构造方法中手动的调用 父类的构造方法。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)