Home > Backend Development > PHP Tutorial > PHP沿袭构造方法,成员变量

PHP沿袭构造方法,成员变量

WBOY
Release: 2016-06-13 13:11:34
Original
911 people have browsed it

PHP继承构造方法,成员变量

发现自己对这些概念一直比较模糊,特总结如下:

?

1.在子类没有构造方法的情况下,默认调用父类的构造方法

?

2.如果子类有构造方法,则不会调用父类的构造方法,并且会覆盖父类的成员变量;如果要调用,则用parent::__construct();

?

3.父类的成员变量和方法默认会被子类所继承

?

eg:

    class A{
        public $a = array();
        public $b = '';
        public function __construct(){
            $this->a = array('a', 'b', 'c');
            $this->b = 'bobby';
            echo 'construct' . "\n";
        }
        public function get(){
            print_r($this->a);
        }
    }

    class B extends A{
        public function __construct(){
            parent::__construct();
            $this->c = 'CC';
        }
        public function get(){
            array_push($this->a, 'd');
            print_r($this->a);
            echo $this->c;
        }
        public function getb(){
            echo parent::$this->b;
        }
    }

    //$a = new A();
    $b = new B();
    $b->get();
    $b->getb();
Copy after login
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