1.4. PHP类的继承

继承: 在定义某个类的时候,可以指定这个类,根据程序中已经存在的某个类派生而来

class Humanity{
	public $name;
	public $sex;
	public $iq=10;
	const BIRTHPLACE='地球';
}

比如新创建的Student类就继承了Humanity这个类

Student 称作是Humanity的子类, Humanity是 Student的父类

子类继承了父类的属性和方法, 就相当于子类中有和父类一样的属性和方法

子类可以再定义属于自己的属性和方法、类常量

class Humanity{
	public $name;
	public $sex;
	public $iq=10;
	const BIRTHPLACE='地球';
}

class Student extends Humanity{
	public $studentId;
	public function test($subject){
		echo "{$this->name}正在考{$subject}!";
	}
}

$hanMM=new Student('韩梅梅','女');
$hanMM->eat('苹果');
$hanMM->test('数学');

如果想改变父类的方法怎么办?

直接去改父类的代码肯定是不好的

方法重写:在子类里面包含和父类同名的方法

重写的方法的参数必须和父类中对应方法的参数一致,构造方法出外部

如果不希望父类中的某些方法被子类重写,在父类定义前加上final表示该类不能被继承,

属性不能定义为final,只有类和方法才能定义为final

比如在Student类里重写eat方法:

public function eat($food){
	echo "{$this->name}正在快速地吃{$food}";
}
//如果在父类的eat方法前加上final试试

string get_parent_class ([mixed $obj])
返回对象或类的父类名,如果在对象的方法内调用,则 obj为可选项

发布了198 篇原创文章 · 获赞 82 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/weixin_38134491/article/details/103326354
1.4
今日推荐