Home > Backend Development > PHP Tutorial > php inheritance_PHP tutorial

php inheritance_PHP tutorial

WBOY
Release: 2016-07-12 09:07:19
Original
1092 people have browsed it

php inheritance

<?php
/*
继承性
    1.面向对象的三大特性之一
    2.开放性,可扩充性
    3.增加代码的重用性
    4.提高了软件的可维护性
     
    php 使弱类型语言,没有重载的概念
     
    子类中重载父类的方法
        子类可以声明和父类相同的方法名,即子类覆盖父类中同名的方法
        在子类中调用父类中被覆盖的方法
            parent::方法名
              
    在子类中编写构造方法,如果父类中也有构造方法,一定要调用父类中的构造方法
    注意:子类中重载的方法,不能低于父类中的访问权限(子类可以放大权限,但不能缩小权限)
    */
    include "./Person.class.php";
     
    class Student extends Person{
        var $school;
         
        function __construct($name="name1",$age =20,$sex="女", $school){
            $this->name=$name;
            $this->age=$age;
            $this->sex=$sex;
            $this->school = $school;
        }
         
        function study(){
            echo $this->age;
            echo $this->name.":我在{$this->school}学习<br>";
        }
         
        /*
            覆盖父类的say(),子类中重载的方法,不能低于父类中的访问权限(子类可以放大权限,但不能缩小权限)
            父类中是public function say(){}
            子类中变成了private function say(){}
            private function say(){
                echo "{$this->name}:我在{$this->school}学习呢,请不要打扰我<br>";
            }
            这时候会报错Fatal error: Access level to Student::say() must be public (as in class Person
        */
         
        public function say(){
            parent::say();
            echo "{$this->name}:我在{$this->school}学习呢,请不要打扰我<br>";
        }
    }
     
    #$student = new Student;
    #$student->school="北京大学附属中学";
    #$student->name="haha";
    #$student->age=32;
    #$student->study();
    #$student->say();
     
    $student2 = new Student("李会东",24,"男","北京大学");
    #echo $student2->school;
    $student2->say();
?>
Copy after login

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1061541.htmlTechArticlephp inheritance?php/*Inheritance 1. One of the three major characteristics of object-oriented 2. Openness and accessibility Scalability 3. Increase code reusability 4. Improve software maintainability php makes a weakly typed language without duplication...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template