子类如何引用父类的构造方法
1、构造函数
void __construct ([ mixed $args [, $... ]] )
构造函数可以接受参数,能够在创建对象时赋值给对象属性
构造函数可以调用类方法或其他函数
构造函数可以调用其他类的构造函数
2、子类继承了父类,输出结果如下图所示
<?php
header('Content-type:text/html;charset=utf-8');
class Base //父类
{
public function __construct() //父类构造函数
{
echo "父类的构造函数"."<br>";
}
}
class Child extends Base //子类
{
public function __construct() //子类构造函数
{
echo "子类的构造函数"."<br>";
}
}
$childClass = new Child(); //对类的实例化
?>
3、第一种引用方法:parent::__construct();
4、代码实例(执行结果如下图所示):
<?php
header('Content-type:text/html;charset=utf-8');
class Base //父类
{
public function __construct() //父类构造函数
{
echo "父类的构造函数"."<br>";
}
}
class Child extends Base //子类
{
public function __construct() //子类构造函数
{
echo "子类的构造函数"."<br>";
parent::__construct(); //调用父类构造函数
} }
$childClass = new Child(); //对类的实例化
?>
5、第二种引用方法:Base::__construct();(Base为父类名称)
6、代码实例(执行结果如下图所示):
<?php
header('Content-type:text/html;charset=utf-8');
class Base //父类
{
public function __construct() //父类构造函数
{
echo "父类的构造函数"."<br>";
}
}
class Child extends Base //子类
{
public function __construct() //子类构造函数
{
echo "子类的构造函数"."<br>";
parent::__construct(); //调用父类构造函数
Base::__construct(); //调用父类构造函数
} }
$childClass = new Child(); //对类的实例化
?>
7、带参数的构造函数(执行结果如下图所示):
<?php
header('Content-type:text/html;charset=utf-8');
class Base{ // 声明类
public $name; // 声明属性
public $sex;
public $age;
function __construct($name,$sex,$age){
$this -> name = $name; // 给属性name赋传进来的值
$this -> sex= $sex;
$this -> age = $age;
}
}
class Information extends Base {
function __construct($name,$sex,$age){
parent::__construct($name,$sex,$age);
echo $this -> name= $name;
}
}
new Information("小明","男","16");
?>