PHP类的继承性 扩展性 extends 重载 覆盖
26
2014-01-21
PHP子类使用extends
继承父类,子类可以将父类中所有的内容都继承过来。
private
是私有的,只能自己用,不能别人用,包括自己的子类也不能用。
protected
是保护权限,只能自己和自己的子类使用。
pubic
是公开权限,自己、子类、内部、外部都可使用。
/** * @url https://www.maosiji.com ds */ class Person { public $name; protected $age; private $sex; private $school; function __construct( $name, $age, $sex ) { $this->name = $name; $this->age = $age; $this->sex = $sex; } public function say() { echo "我的名字是:{$this->name},年龄是:{$this->age},性别是:{$this->sex}。
";} public function eat() { echo 'eating';} public function run() {} public function learn() {} } class Student extends Person { } class Teacher extends Student { // 工资 public $workprice; // 讲课 public function lecture(){ echo "我的名字是:{$this->name},年龄是:{$this->age},性别是:{$this->sex}。
";} } $s = new Teacher('Nox', 32, '女'); $s->say(); $s->lecture(); /* 打印结果: 我的名字是:Nox,年龄是:32,性别是:女。 我的名字是:Nox,年龄是:32,性别是:。 */
重载、覆盖
在子类中可以写与父类同名的方法。
使用Parent::
调用父类的方法。
只要是子类的构造方法,去覆盖父类的构造方法,一定要在子类构造方法内的最上面调用一下父类被覆盖的方法。
权限问题:子类的属性和方法的权限只能大于或等于父类的属性和方法的权限。
/** * @url https://www.maosiji.com ds */ class Person { protected $name; protected $age; protected $sex; function __construct( $name, $age, $sex ) { $this->name = $name; $this->age = $age; $this->sex = $sex; } public function say() { echo "我的名字是:{$this->name},年龄是:{$this->age},性别是:{$this->sex}。
";} public function eat() { echo 'eating';} public function run() {} public function learn() {} } class Student extends Person { protected $school; function __construct( $name, $age, $sex, $school ) { parent::__construct( $name, $age, $sex); $this->school = $school; } public function say() { // Person::say(); Parent::say(); echo "我就读于{$this->school}。
"; } } class Teacher extends Student { // 工资 public $workprice; // 讲课 public function lecture(){ echo "我的名字是:{$this->name},年龄是:{$this->age},性别是:{$this->sex}。
";} } $s = new Teacher('Nox', 32, '女', 'X大学'); $s->say(); /* 打印结果: 我的名字是:Nox,年龄是:32,性别是:女。 我就读于X大学。 */
本文由 猫斯基 原创发布。
著作权均归用户本人所有。独家文章转载,请联系本站管理员。获得授权后,须注明本文地址! 本文地址:https://www.maosiji.com/2555.html