PHPUnit - 将 $this 或 self 用于静态方法?

PHPUnit - Use $this or self for static methods?

我不想写很长的文字,因为这是一个简短的问题。 PHPUnit 测试包含几个静态方法。例如所有 \PHPUnit\Framework\Assert::assert*() methods 以及 identicalToequalTo.

我的 IDE(使用 IntelliSense/autocompletion)不接受使用 $this 的呼叫,但使用自己。我了解到静态函数应该通过 class 调用,而不是对象,所以 self.

哪个更正确?

$this->assertTrue('test');

self::assertTrue('test');

?

(如果“$this”更正确,您能否指出为什么我们不应该使用 "self"?)

PHPUnit 4.8.9: vendor/phpunit/phpunit/src/Framework/Assert.php:

/**
 * Asserts that a condition is true.
 *
 * @param bool   $condition
 * @param string $message
 *
 * @throws PHPUnit_Framework_AssertionFailedError
 */
public static function assertTrue($condition, $message = '')
{
    self::assertThat($condition, self::isTrue(), $message);
}

技术上 static::assertTrue() 是正确的,但断言方法的常见用法是 $this->assertTrue()

通常,self 仅用于引用静态方法和属性(尽管令人困惑的是,您 可以 使用 self 引用非静态方法,以及使用 $this 的静态方法,前提是使用 self 调用的方法不引用 $this。)

<?php
class Test {
    public static function staticFunc() {echo "static ";}
    public function nonStaticFunc() {echo "non-static\n";}
    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"

在处理 $thisself 时要记住继承很重要。 $this 将始终引用当前对象,而 self 引用使用了 self 的 class。现代 PHP 还通过 static 关键字包含 late static binding,其操作方式与静态函数的 $this 相同(并且应该优先于)。

<?php
class Person {
    public static function whatAmI() {return "Human";}    
    public function saySelf() {printf("I am %s\n", self::whatAmI());}
    public function sayThis() {printf("I am %s\n", $this->whatAmI());}
    public function sayStatic() {printf("I am %s\n", 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,看来他们只是使用静态方法 the way they've always done them! Though according to their documentation, your code should work fine 做事。

phpunit 文档说您可以使用任何一个,但不提倡一个优于另一个。所以你选择! https://phpunit.readthedocs.io/en/9.2/assertions.html