批改状态:合格
老师批语:其实继承的词翻译的并不非常的准确, 叫类的扩展更准确, 是不是呀
类的继承与实现,好重要的东西。
<?php
namespace one;
class Person
{
// 属性
public $name ;
public $age ;
public $gender ;
// 方法
public function show(){
return $this->name.$this->gender.$this->age ;
}
// 构造方法
public function __construct($name= '张三',$age= 18,$gender= '男')
{
$this->name=$name;
$this->age=$age;
$this->gender=$gender;
}
}
$p1 = new Person('李四',20,'女');
echo $p1->show();
//子类
class Son extends Person
{
// 属性
public $salary;
// 构造方法
public function __construct($salary,$name = '张三', $age = 18, $gender = '男')
{
parent::__construct($name, $age, $gender);
// 新属性的初始化
$this->salary=$salary;
}
// 扩展的新方法
public function new_show(){
return [$this->name,$this->gender,$this->age,$this->salary];
}
}
//传参按照形参的先后来写,其实有智能提示的。
$son = new Son(3000,'王武',22,'男');
print_r($son->new_show()) ;
class Sunzi extends Son
{
public function new_show()
{
// 这句对新方法没什么用,我就想看看它的用法
echo parent::show();
if ($this->salary>50000&&$this->gender==='女'){
echo"这是个富婆,月薪:".$this->salary;
}
}
}
$sunzi = new Sunzi(50001,'小丽',30,'女');
echo $sunzi->new_show();点击 "运行实例" 按钮查看在线实例
面向对象的三大特性
继承,封装,多态
<?php
namespace one;
const NAME='张三';
class Db{
// 实例属性
public $name;
// 构造方法
public function __construct($name)
{
$this->name=$name;
}
// 实例方法
public function say_hi(){
return $this->name;
}
}
namespace two;
//调用第一个命名空间下的Db类
use one\Db;
const NAME='张三';
$db = new Db('奥巴马');
echo $db->say_hi();点击 "运行实例" 按钮查看在线实例
命名空间就是为了防止命名冲突,在各个目录下定义常量,类,函数,避免全局污染.
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号