PHPUnit - 使用 $this 或 self 作为静态方法?
我不想写长文,因为这是一个简短的问题.PHPUnit 测试包含几个静态方法.例如所有那些 PHPUnitFrameworkAssert::assert*()
方法 以及 identicalTo
、equalTo
.
I don't want to write a long text, because it is a short question. PHPUnit tests contain several methods that are static. For example all those PHPUnitFrameworkAssert::assert*()
methods and also the identicalTo
, equalTo
.
我的 IDE(带有 IntelliSense/autocompletion)不接受使用 $this
的调用,而是使用 self.我了解到静态函数应该通过类调用,而不是对象,所以 self
.
My IDE (with IntelliSense/autocompletion) doesn't accept calls with $this
, but with self. I have learned that static functions should be called through the class, not an object, so self
.
哪个更正确?
$this->assertTrue('test');
或
self::assertTrue('test');
?
(如果$this"更正确,你能指出为什么我们不应该使用self"吗?)
(And if "$this" is more correct, can you maybe point out why we should not use "self"?)
推荐答案
一般情况下,self
仅用于引用静态方法和属性(虽然您可以引用令人困惑使用 self
的非静态方法,以及使用 $this
的静态方法,前提是使用 self
调用的方法不引用 $这个
.)
Generally, self
is only used to refer to static methods and properties (though confusingly you can refer to non-static methods with self
, and to static methods with $this
, provided the methods called with self
don't reference $this
.)
<?php
class Test {
public static function staticFunc() {echo "static ";}
public function nonStaticFunc() {echo "non-static
";}
public function selfCaller() {self::staticFunc(); self::nonStaticFunc();}
public function thisCaller() {$this->staticFunc(); $this->nonStaticFunc();}
}
$t = new Test;
$t->selfCaller(); // returns "static non-static"
$t->thisCaller(); // also returns "static non-static"
在处理 $this
或 self
时要记住继承很重要.$this
将始终引用当前对象,而 self
引用使用 self
的类.现代 PHP 还包括 后期静态绑定 通过 static
关键字,其操作方式与静态函数的 $this
相同(并且应该优先于).
Inheritance is important to remember when dealing with $this
or self
. $this
will always refer to the current object, while self
refers to the class in which self
was used. Modern PHP also includes late static binding via the static
keyword, which will operates the same way as (and should be preferred over) $this
for static functions.
<?php
class Person {
public static function whatAmI() {return "Human";}
public function saySelf() {printf("I am %s
", self::whatAmI());}
public function sayThis() {printf("I am %s
", $this->whatAmI());}
public function sayStatic() {printf("I am %s
", static::whatAmI());}
}
class Male extends Person {
public static function whatAmI() {return "Male";}
}
$p = new Male;
$p->saySelf(); // returns "I am Human"
$p->sayThis(); // returns "I am Male"
$p->sayStatic(); // returns "I am Male"
特别是对于 PHPUnit,他们似乎只是按照他们一直以来的方式做事 !尽管根据他们的文档, 你的代码应该可以正常工作 使用静态方法.
As regards PHPUnit in particular, it appears they simply do things the way they've always done them! Though according to their documentation, your code should work fine using static methods.
相关文章