如何让PHP方法返回mixed和self类型并支持PhpStorm代码提示?
问题描述
现有PHP代码如下:
class Foo { final public function get(string $path): mixed { // return mixed or self type; } final public function otherMethod() { } }
上述代码中,get方法的返回值可以是任意类型,也可以是自身的static实例。但由于返回类型声明为mixed,PhpStorm无法对以下链式调用提供代码提示:
$obj->get('path.to.any.data')->otherMethod();
解决方法
方式一:通过PHPDoc注解补充类型信息
在get方法的PHPDoc块中添加@return注解,明确返回值包含当前类的实例类型:
class Foo { /** * @return mixed|static */ final public function get(string $path): mixed { // return mixed or self type; } final public function otherMethod() { } }
PhpStorm会识别该注解,当执行链式调用时,会针对static类型提供otherMethod()的代码提示,同时保留对mixed类型的兼容性。
方式二:使用PHP 8.0+原生联合类型声明
如果项目基于PHP 8.0及以上版本,可以直接修改方法的返回类型为联合类型,替代mixed:
class Foo { final public function get(string $path): mixed|static { // return mixed or self type; } final public function otherMethod() { } }
原生联合类型无需依赖注解,PhpStorm会直接识别并提供对应的代码提示。
内容的提问来源于stack exchange,提问作者Basil
相关产品推荐
相关产品推荐

