Home > Backend Development > PHP Tutorial > 为什么父类中可以调用子类的方法?

为什么父类中可以调用子类的方法?

WBOY
Release: 2016-06-06 20:38:00
Original
1109 people have browsed it

<code>abstract class A {
        private $name;
        function __construct($param){
            $this->name = 'liming'.'<br>';
        }
        function getName() {
            echo $this->name;
        }

        // 调用子类中的方法getAge2
        function getAge() {
            $this->getAge2();
        }

        function getAge3() {
            return '23';
        }
    }

class B extends A {
    function getAge2(){
        echo $this->getAge3();
    }
}

$a = new B('a');
$a->getName();
$a->getAge();
</code>
Copy after login
Copy after login

回复内容:

<code>abstract class A {
        private $name;
        function __construct($param){
            $this->name = 'liming'.'<br>';
        }
        function getName() {
            echo $this->name;
        }

        // 调用子类中的方法getAge2
        function getAge() {
            $this->getAge2();
        }

        function getAge3() {
            return '23';
        }
    }

class B extends A {
    function getAge2(){
        echo $this->getAge3();
    }
}

$a = new B('a');
$a->getName();
$a->getAge();
</code>
Copy after login
Copy after login

脑袋思维定势了吧,为何不(new A)->getAge()试试?http://3v4l.org/cMZjE

php是弱类型语言,能调什么方法,取决于对象本身是什么类型
这点跟Java不同,Java里一个对象能调什么方法,取决于指向这个对象的引用是什么类型

Related labels:
php
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