簡體   English   中英

PHPDoc 包裝器 object 屬性

[英]PHPDoc wrapper object property

遇到卡住情況,會產生不必要的 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));
  }
}

Controller:

<?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 class 有很多類似reverseName()的方法,因此將data屬性分配給新變量也很難寫: /** @var Customer $john */ $john = (new Customer())->getCustomer()->data

您可以嘗試使用另一個名為高級元數據的 PhpStorm 功能。

首先,您需要通過以下方式配置元數據

namespace PHPSTORM_META {
    override(\App\Result::getData(0), map(['' => '@']));
}

然后將吸氣劑添加到您的Result class

public function getData()
{
    return $this->data;
}

並以接下來的方式使用這個 getter

$john->getData(Customer::class)->reverseName();

主要思想是使用 class 名稱作為 getter 方法的參數,PhpStorm 將知道 class object 這個 getter 將返回什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM