1. 程式人生 > >PHP面向對象程序設計之繼承性

PHP面向對象程序設計之繼承性

調用 truct var_dump 一個 sch span test dump div

一、類繼承的應用
<?php

class A {
    public $name = "zhangsan";
    public $age = 20;

    public function say() {
        return $this -> name;
    }
}

class B extends A {
}

class C extends A {
}

$b = new B ();
var_dump ( $b );
echo $b -> say ();
echo "<hr />";

$c = new C ();
var_dump ( $c
); echo $c -> say (); ?> <?php class person{ public $name; public $age; public $sex; public function __construct($name,$age,$sex){ $this -> name = $name; $this -> age = $age; $this -> sex = $sex; } public function say(){
echo "say..."; } public function eat(){ echo "eat..."; } public function run(){ echo "run..."; } } class teacher extends person{ public function teach(){ echo "teach..."; } } class student extends person{ public function learn(){
echo "learn..."; } } $teacher = new teacher("zhangsan",30,‘nan‘); $teacher -> say(); $teacher -> teach(); echo "<hr>"; $student = new student("lisi",18,‘nv‘); $student -> run(); $student -> learn(); ?> 二、訪問類型的控制 <?php //訪問類的控制的三種類型 class person { public $name; private $age; protected $sex; public function __construct($name, $age, $sex) { $this -> name = $name; $this -> age = $age; $this -> sex = $sex; } public function p1() { echo "p1"; } private function p2() { echo "p2"; } protected function p3() { echo "p3"; } //1.在類中調用 public function test1(){ echo $this -> name; echo $this -> age; echo $this -> sex; } } //2.在子類中調用 class student extends person { public function test() { echo $this -> name; echo $this -> age; echo $this -> sex; } } //3.在類外調用 $person = new person ( "zhangsan", 18, ‘nan‘ ); echo $person -> name; echo $person -> age; echo $person -> sex; ?> 三、子類中重載父類的方法 <?php class person{ public $name; public $age; public $sex; public function __construct($name,$age,$sex){ $this -> name = $name; $this -> age = $age; $this -> sex = $sex; } public function say(){ echo "My name is {$this -> name}, my age is {$this -> age}, my sex is {$this -> sex}"; } } class teacher extends person{ public $teach; public function __construct($name,$age,$sex,$teach){ // $this -> name = $name; // $this -> age = $age; // $this -> sex = $sex; parent::__construct($name,$age,$sex); //這句代碼代替上面的三句 $this -> teach = $teach; } //聲明一個同名的方法,就可以重寫 public function say(){ parent::say(); echo ", my teach is {$this -> teach}"; } } class student extends person{ public $school; public function __construct($name,$age,$sex,$school){ $this -> name = $name; $this -> age = $age; $this -> sex = $sex; $this -> school = $school; } public function say(){ //echo "My name is {$this -> name}, my age is {$this -> age}, my sex is {$this -> sex}, my school is {$this -> school}"; parent::say(); echo ", my school is {$this -> school}"; } } $teacher = new teacher(‘zhangsan‘,30,‘nan‘,‘shuxue‘); $teacher -> say(); echo "<hr>"; $student = new student(‘lisi‘,18,‘nv‘,‘beida‘); $student -> say(); ?>

PHP面向對象程序設計之繼承性