Php构造函数初始化 [英] Php constructor initialization

查看:88
本文介绍了Php构造函数初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Php类初始化有疑问。就像在Java中一样,实例化类调用父类的构造函数来初始化父类以便能够使用它们的属性,PHP不需要我们按顺序调用父类构造函数能够使用它的属性和方法..比如代码:

I have a doubt in Php class initialization.. Like in Java, an instantiated class calls constructor of parent classes to initialize the parent classes to be able to use their properties, PHP need not require us to call Parent Class constructor in order to be able to use its Properties and method.. Like in the code :

class Mammal{
    protected $name = "Hey";
    function __construct(){
        echo "Class of Mammals";
     }
}
class Dog extends Mammal{
    public $ecolor = "Black";
    public $fcolor = "White";
    public $nose = "Sharp";
    function __construct(){
        echo "Lovely Dog <br>";
        echo $this->name . "<br>"; // can call name without parent::__construct()
}
    function showAll(){
        echo "Eye Color : " . $this->ecolor . " fcolor : " . $this->fcolor . " nose : " . $this->nose;
    }
}

我们如何在不使用构造函数初始化的情况下调用Mammal的$ name变量?



我的尝试:



PHP父构造函数初始化

How are we able to call $name variable of Mammal without initializing it using constructor?

What I have tried:

PHP parent constructor initialization

推荐答案

name =嘿;
function __construct(){
echo哺乳动物类;
}
}
class Dog延伸哺乳动物{
public
name = "Hey"; function __construct(){ echo "Class of Mammals"; } } class Dog extends Mammal{ public


ecolor =Black;
public
ecolor = "Black"; public


fcolor =White;
public
fcolor = "White"; public


这篇关于Php构造函数初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆