2016-03-01 74 views
-1

我学习PHP类和对象,但这些代码混淆了我:为什么是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()得到不同的输出?

请详细描述。

+0

的可能的复制[何时使用自超过$吗?(HTTP:/ /stackoverflow.com/questions/151969/when-to-use-self-over-this) – mitkosoft

+0

因为'self :: load()'引用了__class的'load()'方法,其中方法在继承中被调用___树;而'$ this-> load()'引用__instance__的load方法,并且通过继承'''''load''方法覆盖实例的'''load()'方法 –

回答

0

让我们开始吧。

Self选择当前班级。

this选择当前对象。

所以当你使用self::load();它,当你使用$this->load();意思加载功能在A级

在另一方面class B->load

相关问题