__construct
作为类的构造函数,这样做的好处就是构造函数无需随着类名的改变而做出修改。在 PHP7.0 中废弃了 PHP3.0 和 PHP4.0 中的用法,构造函数必须使用 __construct
来定义。 new Students($name, $age)
。
public function __construct(参数列表){
... ...
}
注意:如果显式地声明构造函数,那么它的访问权限必须是 public,而且构造函数是在实例化时自动调用的,我们不需要手动调用。
【示例】创建一个类,并为其显示的创建构造函数,代码如下:<?php class Website{ public $name, $url, $title; public function __construct($str1, $str2, $str3){ $this -> name = $str1; $this -> url = $str2; $this -> title = $str3; $this -> demo(); } public function demo(){ echo $this -> name.'<br>'; echo $this -> url.'<br>'; echo $this -> title.'<br>'; } } $object = new Website('C语言中文网','http://c.biancheng.net/php/','构造函数'); ?>运行结果如下:
C语言中文网
http://c.biancheng.net/php/
构造函数
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有