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 的详细介绍请点这里
PHP 的下载地址请点这里

猜你喜欢

转载自www.linuxidc.com/Linux/2017-01/139134.htm