php构造方法和java构造方法有什么区别

 3995

区别:1、重写子类构造函数时,PHP不调用父类,而java默认在第一个语句前调用父类构造方法;2、Java允许有多个构造方法,而PHP值允许有一个构造方法;3、Java中的构造方法是必须的,而PHP中的不是。


php构造方法和java构造方法有什么区别


php构造方法和java构造方法有什么区别

早期的PHP是没有面向对象功能的,但是随着PHP发展,从PHP4开始,也加入了面向对象。PHP的面向对象语法是从JAVA演化而来,很多地方类似,但是又发展出自己的特色。以构造函数来说,PHP4中与类同名的函数就被视为构造函数(与JAVA一样),但是PHP5中已经不推荐这种写法了,推荐用__construct来作为构造函数的名称。


1、重写子类构造函数的时候,PHP会不调用父类,JAVA默认在第一个语句前调用父类构造函数

JAVA

  1. class Father{
  2.     public Father(){
  3.         System.out.println("this is fahter");
  4.     }
  5. }
  6. class Child extends Father{
  7.     public Child(){
  8.         System.out.println("this is Child");
  9.     }
  10. }
  11. public class Test {
  12.     public static void main(String[] args){
  13.         Child c = new Child();
  14.     }
  15. }

输出结果:

this is fahter

this is Child


PHP代码

  1. <?php
  2. class Father{
  3.     public function __construct(){
  4.         echo "正在调用Father";
  5.     }
  6. }
  7. class Child extends Father{
  8.     public function __construct(){
  9.         echo "正在调用Child";
  10.     }
  11. }
  12. $c = new Child();

输出结果:

正在调用Child


2、重载的实现方式

JAVA允许有多个构造函数,参数的类型和顺序各不相同。PHP只允许有一个构造函数,但是允许有默认参数,无法实现重载,但是可以模拟重载效果。

JAVA代码

  1. class Car{
  2.     private String _color;
  3.     //设置两个构造函数,一个需要参数一个不需要参数
  4.     public Car(String color){
  5.         this._color = color;
  6.     }
  7.      
  8.     public Car(){
  9.         this._color = "red";
  10.     }
  11.      
  12.     public String getCarColor(){
  13.         return this._color;
  14.     }
  15. }
  16. public class TestCar {
  17.     public static void main(String[] args){
  18.         Car c1 = new Car();
  19.         System.out.println(c1.getCarColor());
  20.         //打印red
  21.          
  22.         Car c2 = new Car("black");
  23.         System.out.println(c2.getCarColor());
  24.         //打印black
  25.     }
  26. }

PHP代码

  1. <?php
  2. class Car{
  3.     private $_color;
  4.     //构造函数带上默认参数
  5.     public function __construct($color="red"){
  6.         $this->_color = $color;
  7.     }
  8.     public function getCarColor(){
  9.         return $this->_color;
  10.     }
  11. }
  12. $c1 = new Car();
  13. echo $c1->getCarColor();
  14. //red
  15. $c2 = new Car('black');
  16. echo $c2->getCarColor();
  17. //black

3、JAVA中构造函数是必须的,如果没有构造函数,编译器会自动加上,PHP中则不会。

4、JAVA中父类的构造函数必须在第一句被调用,PHP的话没有这个限制,甚至可以在构造函数最后一句后再调用。

5、可以通过this()调用另一个构造函数,PHP没有类似功能。

  1. class Pen{
  2.     private String _color;
  3.     public Pen(){
  4.              this("red");//必须放在第一行
  5.     }
  6.      
  7.     public Pen(String color){
  8.         this._color = color;
  9.     }
  10. }


TAG标签:
本文网址:https://www.zztuku.com/detail-11188.html
站长图库 - php构造方法和java构造方法有什么区别
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐