Demo12.php
<?php
header ( 'Content-Type:text/html; charset=utf-8;' );
//这是父类,电脑类
class Computer {
public $_name = '联想';
public function _run(){
echo '联想在运行!';
}
}
//子类,笔记本电脑类
class NoteComputer extends Computer {
}
$noteComputer = new NoteComputer();
echo $noteComputer -> _name;
$noteComputer -> _run();
?>
Demo13.php
<?php
header ( 'Content-Type:text/html; charset=utf-8;' );
class Computer {
public $_name = '联想';
public function _run(){
echo '联想在运行!';
}
}
class NoteComputer extends Computer {
//我不需要父类的字段和方法,那么可以采用重写的方法覆盖掉父类的字段和方法
public $_name = 'Dell';
public function _run(){
echo 'Dell在运行!';
}
}
$noteComputer = new NoteComputer();
echo $noteComputer -> _name;
$noteComputer -> _run();
?>
Demo14.php
<?php
header ( 'Content-Type:text/html; charset=utf-8;' );
class Computer {
//私有化,但是无法被子类继承,这个时候就应该用受保护的修饰符来封装
protected $_name = '联想';
protected function _run(){
return '联想在运行!';
}
}
class NoteComputer extends Computer {
public function getTop() {
echo $this->_name;
echo $this->_run();
}
}
$noteComputer = new NoteComputer();
$noteComputer -> getTop();
?>
Demo15.php
<?php
header ( 'Content-Type:text/html; charset=utf-8;' );
class Computer {
public $_name = '联想';
public function _run(){
return '联想在运行!';
}
}
class NoteComputer extends Computer {
//我子类已经覆盖了父类的字段和方法,
//但是我又要调用父类的字段和方法,那怎么办呢?
public $_name = 'Dell';
public function _run(){
echo 'Dell在运行!';
echo parent :: _run();
}
}
$noteComputer = new NoteComputer();
echo $noteComputer -> _name;
$noteComputer -> _run();
//DellDell在运行!联想在运行!
?>
Demo16.php
<?php
header ( 'Content-Type:text/html; charset=utf-8;' );
//final 如果加在类前面,表示这个类不能被继承
// final class Computer {
// }
class Computer {
//final 如果加在方法前面,表示不能够重写些方法
final public function _run(){
}
}
class NoteComputer extends Computer {
public function _run(){
}
}
$noteComputer = new NoteComputer();
?>
Demo17.php
<?php
header ( 'Content-Type:text/html; charset=utf-8;' );
//创建一个抽象类,只要在 class 前面加上 abstract 就是抽象类了
//抽象类不能够被实例化,就是创建对象
//只在类里面有一个抽象方法,那么这个类必须是抽象类,类前面必须加上 abstract
abstract class Computer {
public $_name = '联想';
//抽象类里创建一个抽象方法
//抽象方法不能够实现方法体的内容
abstract public function _run();
//我在抽象类里能否创建一个普通方法
public function _run2(){
echo '我是父类的普通方法';
}
}
//类不能够实现多继承,只支持单继承。
//抽象类是给子类用来继承的,实现一种规范和资源的共享
class NoteComputer extends Computer {
//抽象类的抽象方法,子类必须重写,不然会报错。
//抽象类里的普通方法不需要重写,子类会直接继承下来
public function _run(){
echo '我是子类的方法';
}
}
$noteComputer = new NoteComputer();
$noteComputer -> _run();
$noteComputer -> _run2();
echo $noteComputer -> _name;
?>







