我有这种情况:
class A extends B {
public function test() {
parent::test();
}
}
class B extends someCompletelyOtherClass {
public function test() {
//what is the type of $this here?
}
}
功能测试中B类$this的类型是什么?A 还是 B?我试过了,它的 A,我在想它的 B?为什么是A?
谢谢!
我不是PHP专家,但我认为这是有道理的。 $this应指向类型 A 的实例化对象,即使该方法是在类 B 中定义的。
如果创建类 B 的实例并直接调用它的测试方法,则$this应指向 B 类型的对象。
问题是你是在静态调用test()
,即在类上下文中。静态调用非静态函数是一个错误(不幸的是,PHP 没有强制执行这一点)。
你应该使用$this->test()
,而不是parent::test()
。
在 PHP 中,关键字 "$this" 用作类的自引用,您可以使用它来调用和使用类函数和变量。 下面是一个例子:
class ClassOne
{
// this is a property of this class
public $propertyOne;
// When the ClassOne is instantiated, the first method called is
// its constructor, which also is a method of the class
public function __construct($argumentOne)
{
// this key word used here to assign
// the argument to the class
$this->propertyOne = $argumentOne;
}
// this is a method of the class
function methodOne()
{
//this keyword also used here to use the value of variable $var1
return 'Method one print value for its '
. ' property $propertyOne: ' . $this->propertyOne;
}
}
当你调用 parent::test() 时,你实际上是在调用与 CLASS B 关联的测试函数,因为你是静态调用它的。 尝试称它为 $this->test(),你应该得到 A 而不是 B。