为什么是php程序的输出?

时间:2016-03-01 08:16:05

标签: php class object

我正在学习PHP的类和对象,但这些代码让我困惑:

<?php
class A
{
    public function test()
    {
        //output will be A load(), why?
        self::load();
        //output will be B load(), why?
        $this->load();
    }
    public function load()
    {
        echo "A load()";
    }
}

class B extends A
{
    public function test()
    {
        parent::test();
    }
    public function load()
    { 
        echo "B load()";
    }
}
$c  = new B();
$c->test();

在这种情况下,为什么self::load()$this->load()获得不同的输出?

请详细说明。

2 个答案:

答案 0 :(得分:5)

这是因为self使用它所定义的类。整个过程都在这里记录:http://php.net/manual/en/language.oop5.late-static-bindings.php

使用selfstatic之间存在差异。请注意您的代码,通常需要将方法测试定义为静态,以便使用self::test();进行调用。

答案 1 :(得分:0)

让我们开始吧。

Self选择当前班级。

this选择了当前对象。

所以当你使用self::load();时,它会在A类中加载函数

另一方面,当您使用$this->load();时,

表示class B->load