我有静态方法的类,我需要将其更改为单元测试的实例方法。然而,我不能改变静态调用它们的代码。所以我试图实现一个门面(类似于Laravel所做的),这样我就可以静态和动态地调用函数。我的代码本身是工作的,但PHPStorm抱怨静态调用。下面是我的facade类,它带有一个test子类和一个phpunit测试:
abstract class Facade
{
/**
* Handle dynamic, static calls to the object.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public static function __callStatic($method, $parameters)
{
$instance = new static;
return call_user_func_array([$instance, $method], $parameters);
}
}
class Foo extends Facade
{
/**
* @param string $param1
* @return string
*/
public function TestMethod1($param1)
{
return 'Test: '.$param1;
}
}
class FooTest extends 'PHPUnit_Framework_TestCase
{
public function testFacade()
{
$param1 = 'ok';
$result = Foo::TestMethod1($param1);
$this->assertEquals('Test: '.$param1, $result);
}
}
我试过使用phpdoc @method对Foo和@static对TestMethod1方法,但似乎都不起作用。我怎样才能让PHPStorm停止抱怨静态调用?除了关闭检查,还有别的办法吗?
我的代码本身正在工作,
它只工作,因为你不在TestMethod1
中使用$this
,并且没有在严格模式下运行测试。
__callStatic
永远不会被调用,因为Foo::TestMethod1()
引用了现有的方法,即使它没有被声明为static。
试一试:
https://3v4l.org/rsR71class T
{
public static function __callStatic($method, $args)
{
echo "__callStatic() called'n";
}
public function f()
{
echo "f() called'n";
}
}
T::f();
hhvm-3.6.1 - 3.9.0的输出
f() called
7.0.0alpha1 - 7.0.0rc3的输出
Deprecated: Non-static method T::f() should not be called statically in /in/rsR71 on line 15
f() called
5.4.8 - 5.6.13
Strict Standards: Non-static method T::f() should not be called statically in /in/rsR71 on line 15
f() called