我正在学习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 :(得分:5)
这是因为self
使用它所定义的类。整个过程都在这里记录:http://php.net/manual/en/language.oop5.late-static-bindings.php
使用self
和static
之间存在差异。请注意您的代码,通常需要将方法测试定义为静态,以便使用self::test();
进行调用。
答案 1 :(得分:0)
让我们开始吧。
Self
选择当前班级。
this
选择了当前对象。
所以当你使用self::load();
时,它会在A类中加载函数
$this->load();
时,表示class B->load