【问题标题】:Add PHP Dynamic Methods in IDE Autocomplete在 IDE 自动完成中添加 PHP 动态方法
【发布时间】:2020-01-08 04:00:56
【问题描述】:

我需要在我的 PHP 类中创建一些动态方法。

使用这个类:

class SampleClassWithDynamicMethod
{
    public function __call($methodName, $values)
    {
        if(!method_exists($this, $methodName)){
            // Do something...
            return "You called $methodName!";
        }
    }

$sample = new SampleClassWithDynamicMethod();
echo $sample->test(); 
// You called test!

echo $sample->anotherTest();
// You called anotherTest!

echo $sample->moreTest(); 
// You called moreTest!

效果很好。但是我怎样才能让 IDE 知道这个类有这些名称的动态方法:test()anotherTest()moreTest()

【问题讨论】:

  • 如果你有特定的方法,你为什么不想在你的类中实际声明它们。即使它们只是通过主存根,它也会更清晰(恕我直言)。
  • @NigelRen 我有超过 25 种不同的方法。我可以手动添加所有这些,但我认为这会使我的代码变得嘈杂,如果我认为正确的话

标签: php autocomplete ide


【解决方案1】:

您可以使用 PHP DocBlocks。主要的 PHP IDE 都支持这些。

具体来说,@method 注释。检查docs

使用文档中的示例:

/**
  * @method string getString()
  * @method void setInteger(integer $integer)
  * @method setString(integer $integer)
  * @method static string staticGetter()
  */
 class Child extends Parent
 {
     // <...>
 }

这将声明它可以执行以下任何操作,这将被 IDE 识别并提供自动完成功能(显然,假设方法已以某种方式实现):

$child = new Child();
$child->setInteger(10);
$child->setString(2);
echo $child->getString();
// 2

$string = Child::staticGetter();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 2020-06-05
    • 2016-09-16
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多