PHP与Java构造函数的差异
发布时间:2021-11-18 10:40:45 所属栏目:PHP教程 来源:互联网
导读:早期的PHP是没有面向对象功能的,但是随着PHP发展,从PHP4开始,也加入了面向对象。PHP的面向对象语法是从Java演化而来,很多地方类似,但是又发展出自己的特色。以构造函数来说,PHP4中与类同名的函数就被视为构造函数(与JAVA一样),但是PHP5中已经不推荐这
|
早期的PHP是没有面向对象功能的,但是随着PHP发展,从PHP4开始,也加入了面向对象。PHP的面向对象语法是从Java演化而来,很多地方类似,但是又发展出自己的特色。以构造函数来说,PHP4中与类同名的函数就被视为构造函数(与JAVA一样),但是PHP5中已经不推荐这种写法了,推荐用__construct来作为构造函数的名称。 1.重写子类构造函数的时候,PHP会不调用父类,JAVA默认在第一个语句前调用父类构造函数 JAVA class Father{ public Father(){ System.out.println("this is fahter"); } } class Child extends Father{ public Child(){ System.out.println("this is Child"); } } public class Test { public static void main(String[] args){ Child c = new Child(); } } 输出结果: this is fahter this is Child <?php class Father{ public function __construct(){ echo "正在调用Father"; } } class Child extends Father{ public function __construct(){ echo "正在调用Child"; } } $c = new Child(); 输出结果: 正在调用Child 2.重载的实现方式 JAVA允许有多个构造函数,参数的类型和顺序各不相同。PHP只允许有一个构造函数,但是允许有默认参数,无法实现重载,但是可以模拟重载效果。 JAVA代码 class Car{ private String _color; //设置两个构造函数,一个需要参数一个不需要参数 public Car(String color){ this._color = color; } public Car(){ this._color = "red"; } public String getCarColor(){ return this._color; } } public class TestCar { public static void main(String[] args){ Car c1 = new Car(); System.out.println(c1.getCarColor()); //打印red Car c2 = new Car("black"); System.out.println(c2.getCarColor()); //打印black } } PHP代码 <?php class Car{ private $_color; //构造函数带上默认参数 public function __construct($color="red"){ $this->_color = $color; } public function getCarColor(){ return $this->_color; } } $c1 = new Car(); echo $c1->getCarColor(); //red $c2 = new Car('black'); echo $c2->getCarColor(); //black 3.JAVA中构造函数是必须的,如果没有构造函数,编译器会自动加上,PHP中则不会。 4.JAVA中父类的构造函数必须在第一句被调用,PHP的话没有这个限制,甚至可以在构造函数最后一句后再调用。 5.可以通过this()调用另一个构造函数,PHP没有类似功能。 class Pen{ private String _color; public Pen(){ this("red");//必须放在第一行 } public Pen(String color){ this._color = color; } } ![]() (编辑:应用网_丽江站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |




浙公网安备 33038102330468号