PHP面向对象之继承

继承

  • 介绍

    • 继承使得代码具有层次结构
    • 子类继承了父类的属性和方法,实现了代码的可重用性
    • 使用extends关键字实现继承
    • 父类和子类是相对的
  • 语法

class 子类 extends 父类 {

}
  • 执行过程
    • 第一步:在Student类中查找show(),如果找到就调用,找不到就到父类中查找
    • 第二步:在Person类中查询show()
<?php
class Person {
	public function show() {
		echo "嘿,人类!<br>";
	}
}
class Student extends Person{

} 
$stu= new Student();
$stu->show();
?>

子类中调用父类成员

  • 方法
    • 通过实例化父类调用父类的成员
    • 通过$this关键字调用父类的成员
<?php
class Person {
	public function show() {
		echo "嘿,人类!<br>";
	}
}
class Student extends Person{
  public function test1(){
    $person= new Person();
    $person->show();
  }
  public function test2(){
    $this->show();
  }
} 

$stu1= new Student();
$stu1->test1();
echo '<br>';
$stu2= new Student();
$stu2->test2();
?>

protected

  • protected
    • 受保护的,在整个继承链上使用
<?php
class A {
  //在整个继承链上访问
	protected $num= 10;	
}
class B extends A {	
	public function getNum() {
		echo $this->num;
	}
}
//整个继承链上有A和B
$obj= new B();    
$obj->getNum();	
?>
<?php
class A {
  public function getNum() {
		echo $this->num;
	}
}
class B extends A {	
	//在整个继承链上访问
	protected $num= 10;	
}
//整个继承链上有A和B
$obj= new B();    
$obj->getNum();	
?>
<?php
class A {
  public function getNum() {
		echo $this->num;
	}
}
class B extends A {	
	//在整个继承链上访问
	protected $num= 10;	
}
//整个继承链上只有A
$obj= new A();    
$obj->getNum();	
?>

继承中的构造函数

  • 规则

    • 如果子类有构造函数就调用子类的,如果子类没有就调用父类的构造函数
    • 子类的构造函数调用后,默认不再调用父类的构造函数
  • 语法

    • 通过类名调用父类的构造函数
    • parent关键字表示父类的名字,可以降低程序的耦合性
# 通过类名调用父类的构造函数
父类类名::__construct();

# 通过parent关键字调用父类的构造函数
parent::__construct();
<?php
class Person {
  //父类的构造函数
  public function __construct() {
    echo '这是父类<br>';
  }
}
class Student extends Person {
  //子类的构造函数
  public function __construct() {
    //通过父类的名字调用父类的构造函数
    Person::__construct();
    //parent表示父类的名字		
    parent::__construct();		
    echo '这是子类<br>';
  }
}
new Student();
?>
  • 案例
<?php
class Person {
	protected $name;
	protected $sex;
    //父类的构造函数
	public function __construct($name, $sex) {
		$this->name= $name;
		$this->sex= $sex;
	}
}
class Student extends Person {
	private $score;
    //子类的构造函数
	public function __construct($name, $sex, $score) {
		parent::__construct($name, $sex);  //调用父类构造函数并传递参数
		$this->score= $score;
	}
    //显示信息
	public function getInfo() {
		echo "姓名:{$this->name}<br>";
		echo "性别:{$this->sex}<br>";
		echo "成绩:{$this->score}";
	}
}
//测试
$stu=new Student('sunny','男',28);
$stu->getInfo();
?>

$this详解

  • 概念
    • $this表示当前对象的引用,也就是$this保存的当前对象的地址
<?php
class A {
	public function __construct(){
		var_dump($this);
	}
}
class B extends A {
	
}
new A();
echo '<br>';
new B();
?>

多重继承

  • 概念
    • PHP不允许多重继承,因为多重继承容易产生二义性
    • 如何实现C继承A和B,使用继承链
原文地址:https://www.cnblogs.com/SharkJiao/p/14117053.html