【发布时间】:2021-07-13 23:59:34
【问题描述】:
遇到了一个卡住的情况,会产生不必要的 IDE 警告,并可能导致清理使用过的代码。
我认为最好的解决方案是在正确的位置添加一些 PHPDoc,但由于某些限制而无法找到正确的位置,如下面的示例所述。
IDE:PhpStorm
结果:
<?php
/*
* Generic result class, widely used, so can't touch it ¯\_(ツ)_/¯
*/
class Result {
public $data;
public function __construct() {
return $this;
}
public function setData($data) {
$this->data = $data;
return $this;
}
}
客户:
<?php
class Customer {
public string $name = '';
public string $email = '';
public function __construct() {
$this->name = 'John Smith';
$this->email = 'test@example.com';
}
public function getCustomer(): Result {
return (new Result())->setData(new self());
}
public function reverseName(): string { // ❌ Unused element: 'reverseName'
$parts = explode(' ', $this->name);
return implode(' ', array_reverse($parts));
}
}
控制器:
<?php
require_once 'vendor/autoload.php';
$john = (new Customer())->getCustomer();
// ℹ️ $john->data is an instance of the Customer class.
// How should I tell to the IDE this ^ ❓
$reversedName = $john->data->reverseName(); // ❌ Cannot find declaration to go when trying to navigate to the method
exit($reversedName);
尝试了很多很多选项,但唯一有效的方法是将 PHPDoc 添加到 Result 的 $data 属性。不能碰它,因为它在项目中被广泛使用...
LE::Customer类有很多类似reverseName()的方法,所以将data属性赋值给一个新变量也很难写:/** @var Customer $john */ $john = (new Customer())->getCustomer()->data;
【问题讨论】:
-
/** @var Customer $johnData */$johnData = (new Customer())->getCustomer()->data;-- 类似这样的东西。基本上:将$object->data放入一个单独的变量中并输入提示。 -
确实,这也行,但是有很多代码需要重构。更新了问题。谢谢!
-
当this 可用时,应该很快可以通过 Psalm 或 PHPstan 实现(应该很快)。