先给出个简答的例子:

<?php

class ParentClass
{
    public function one()
    {
        echo 'parent here<br />';
    }

    public function alone()
    {
        echo 'alone<br />';
        $this->one();
    }
}

class ChildClass extends ParentClass
{
    public function one()
    {
        echo 'child here<br />';
    }

    public function test()
    {
        $this->alone();
    }
}

$child = new ChildClass();
$child->test();

//输出
alone
child here

注意在子类中实例中调用父类的方法,如果父类方法中包含子类重载后的方法时,会优先调用子类方法。如果子类中没有此方法时,才会调用父类的方法。

<?php

class ParentClass
{
    public function one()
    {
        echo 'parent here<br />';
    }

    public function alone()
    {
        echo 'alone<br />';
        $this->one();
    }
}

class ChildClass extends ParentClass
{
    // public function one()
    // {
    //     echo 'child here<br />';
    // }

    public function test()
    {
        $this->alone();
    }
}

$child = new ChildClass();
$child->test();

//输出
alone
parent here

这样的行为,在python中也同样成立:

class ParentClass:
    def one(self):
        print "parent here"
        
    def alone(self):
        print "alone"
        self.one()
        

class ChildClass(ParentClass):
    def one(self):
        print "child here"
        
    def test(self):
        self.alone()
        
c = ChildClass()
c.test()

//输出
alone
child here

还有一个特性值得注意的是:在C和C++里,父类都不允许调用子类的方法,但在php里可以。
下面是一个调用的例子:

<?php
class Animal
{
    protected $name;
    public function run()
    {
        echo 'Aniaml run';
        $this->swim();
        echo $this->fishNum;

    }
}

class Fish extends Animal
{
   public $fishNum=10;
    public function swim()
    {
        echo 'Fish swim';
    }
}
$fish=new Fish();
$fish->swim();
$fish->run();

//输出
Fish swimAniaml runFish swim10

参考网站:



登陆发表评论