區別:1、重寫子類構造函數時,PHP不調用父類,而java默認在第一個語句前調用父類構造方法;2、Java允許有多個構造方法,而PHP值允許有一個構造方法;3、Java中的構造方法是必須的,而PHP中的不是。
本文操作環境:Windows10系統、PHP7.1版、Dell G3電腦。
php構造方法和java構造方法有什么區別
早期的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; } }
推薦學習:《PHP視頻教程》