2

I have classes with static methods that I need to change to instance methods for unit testing. However I can not change the code that calls them statically. So I'm trying to implement a facade (similar to what Laravel does) so that I can call the functions both statically and dynamically. My code itself is working, but PHPStorm is complaining about the static calls. Here is my facade class with a test child class and phpunit test:

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);
    }
}

I have tried using phpdoc @method on Foo and @static on the TestMethod1 method, but neither seems to work. How can I get PHPStorm to stop complaining about the static calls? Is there a way to handle this other than turning off the inspection?

4

1 回答 1

2

我的代码本身正在运行,

它之所以有效,是因为您不使用$thisinsideTestMethod1也不在严格模式下运行测试。

__callStatic永远不会被调用,因为Foo::TestMethod1()引用了一个现有的方法,即使它没有被声明为静态的。

试试看:

https://3v4l.org/rsR71

class 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
于 2015-09-22T19:08:15.063 回答