如何为PHPStan通过注解标记__call方法的可选参数?
如何为PHPStan标注带有可选参数的__call动态方法?
在类的DocBlock注释的@method标签里,直接按照PHP普通方法的语法标注可选参数即可——给参数加上默认值声明,PHPStan完全支持这种写法。
比如你要标注myFunction的第二个参数是可选的int类型,默认值为0,写法如下:
/** * @method mixed myFunction(string $a, int $b = 0) */ class MyClass { public function __call(string $name, array $arguments) { if (!in_array($name, ['myFunction'])) { throw new \BadMethodCallException("Unsupported method: {$name}"); } // 你的__call逻辑实现 } }
不同场景的可选参数标注示例
- 可选参数为字符串默认空值:
@method mixed myFunction(string $a, string $b = '') - 可选参数允许为null且默认值是null:
@method mixed myFunction(string $a, ?int $b = null) - 多个可选参数:
@method mixed myFunction(string $a, int $b = 0, bool $c = true)
这样标注后,PHPStan就能正确识别动态方法的参数规则,不管你是传入全部参数还是省略可选参数,都不会再抛出Call to an undefined method的错误。
内容的提问来源于stack exchange,提问作者neubert
相关产品推荐
相关产品推荐

