Welcome 微信登录

首页 / 操作系统 / Linux / PHP与Java构造函数的区别

早期的PHP是没有面向对象功能的,但是随着PHP发展,从PHP4开始,也加入了面向对象。PHP的面向对象语法是从JAVA演化而来,很多地方类似,但是又发展出自己的特色。以构造函数来说,PHP4中与类同名的函数就被视为构造函数(与JAVA一样),但是PHP5中已经不推荐这种写法了,推荐用__construct来作为构造函数的名称。1.重写子类构造函数的时候,PHP会不调用父类,JAVA默认在第一个语句前调用父类构造函数JAVAclass 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<?phpclass Father{public function __construct(){echo "正在调用Father";}}class Child extends Father{public function __construct(){echo "正在调用Child";}}$c = new Child();输出结果:
正在调用Child2.重载的实现方式
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());//打印redCar c2 = new Car("black");System.out.println(c2.getCarColor());//打印black}}PHP代码<?phpclass 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();//black3.JAVA中构造函数是必须的,如果没有构造函数,编译器会自动加上,PHP中则不会。
4.JAVA中父类的构造函数必须在第一句被调用,PHP的话没有这个限制,甚至可以在构造函数最后一句后再调用。
5.可以通过this()调用另一个构造函数,PHP没有类似功能。class Pen{private String _color;public Pen(){ this("red");//必须放在第一行}public Pen(String color){this._color = color;}}
Ubuntu 16.10 开启PHP错误提示  http://www.linuxidc.com/Linux/2016-10/136537.htmUbuntu 16.04环境中安装PHP7.0 Redis扩展 http://www.linuxidc.com/Linux/2016-09/135631.htm在 CentOS 7.x / Fedora 21 上面体验 PHP 7.0  http://www.linuxidc.com/Linux/2015-05/117960.htm CentOS 6.3 安装LNMP (PHP 5.4,MyySQL5.6) http://www.linuxidc.com/Linux/2013-04/82069.htm 在部署LNMP的时候遇到Nginx启动失败的2个问题 http://www.linuxidc.com/Linux/2013-03/81120.htm PHP源码安装、简单配置、测试及连接数据库 http://www.linuxidc.com/Linux/2016-10/135977.htm《细说PHP》高清扫描PDF+光盘源码+全套教学视频 http://www.linuxidc.com/Linux/2014-03/97536.htm CentOS 7.2下编译安装PHP7.0.10+MySQL5.7.14+Nginx1.10.1  http://www.linuxidc.com/Linux/2016-09/134804.htmPHP 的详细介绍:请点这里
PHP 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-01/139134.htm