为什么是php程序的输出?
问题描述:
我学习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()
得到不同的输出?
请详细描述。
答
这是因为self
使用它定义的类所属的类。整个事情在这里记录:http://php.net/manual/en/language.oop5.late-static-bindings.php
使用self
和static
有一个不同。注意你的代码,通常方法测试需要被定义为静态的,用self::test();
来调用它。
答
让我们开始吧。
Self
选择当前班级。
this
选择当前对象。
所以当你使用self::load();
它,当你使用$this->load();
意思加载功能在A级
在另一方面class B->load
的可能的复制[何时使用自超过$吗?(HTTP:/ /*.com/questions/151969/when-to-use-self-over-this) – mitkosoft
因为'self :: load()'引用了__class的'load()'方法,其中方法在继承中被调用___树;而'$ this-> load()'引用__instance__的load方法,并且通过继承'''''load''方法覆盖实例的'''load()'方法 –