public function __construct($name="",$sex="男",$age=27){ //显示声明一个构造方法且带参数 $this->name=$name; $this->sex=$sex; $this->age=$age;
}
public function say(){
echo "我叫:".$this->name.",性别:".$this->sex.",年龄:".$this->age;
}
}
?>
创建对象$Person1且不带任参数
$Person1= new Person();
echo $Person1->say();//输出:我叫:,性别:男,年龄:27
创建对象$Person2且带参数"张三"
$Person2= new Person("张三");
echo $Person2->say();//输出:我叫:张三,性别:男,年龄:27
创建对象$Person3且带三个参数
$Person3= new Person("李四","男",25);
在该例子中,通过构造方法对对象属性进行初始化赋值。
【示例2】
<?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/
构造函数