这是我的测试:
<?php
require __DIR__ . '/vendor/autoload.php';
class HasStatic {
public static function static_method() {
return true;
}
}
class SUT {
public $has_static;
public function __construct() {
$this->has_static = new HasStatic();
}
public function call_static() {
// A parse error :<
// $this->has_static::static_method();
$has_static = $this->has_static;
return $has_static::static_method();
}
}
class PhpStaticCallOnProperty extends PHPUnit_Framework_TestCase {
public function testPhpStaticCallOnProperty() {
$sut = new SUT();
$this->assertTrue($sut->call_static(), 'call_static() succeeded');
}
}
如您所见,我发现$this->has_static::static_method();
会产生解析错误。
有没有一种干净的方法可以在没有额外分配的情况下进行此调用?
静态方法是功能的黑匣子,您可以在其中显式定义所有内容(参数)和输出(返回值)。因此,它们不绑定到对象 - 并且不应使用对象引用调用它们。 static_method()
只能使用 HasStatic::static_method()
或HasStatic
类中的self::static_method()
来调用。
静态方法本身并没有什么问题 - 我强烈反对tereško说应该避免它们。如果一个方法不需要对象的上下文,它也可以是静态的。
发生解析错误的原因是没有理由对属性使用范围解析运算符 (::
)。变量类名确实意味着以下内容将起作用:
$foo = 'HasStatic';
$foo::static_method(); // equivalent to HasStatic::static_method()
但是,该变量不能是属性 - 如果要以这种方式调用该方法,则必须将其分配给临时变量。