PHP: Variable function name (function pointer) cal

2020-02-27 03:35发布

问题:

I'm currently trying to remove all errors and warnings I have in my project the Inspection tool from my PHPStorm give to me.

I encounter a snippet PHPStorm says "Unused private method _xxx" while it's actually used, but in a dynamical way. Here is a simplifyed snippet:

<?php
class A
{
    private function _iAmUsed()
    {
        //Do Stuff...
    }

    public function run($whoAreYou)
    {
        $methodName = '_iAm' . $whoAreYou;
        if (method_exists($this, $methodName)) {
            $this->$methodName();
        }
    }
}

$a = new A();
$a->run('Used');
?>

In this snippet, PHPStorm will tell me "Unused private method _iAmUsed" while, in fact, it is used... How can I, by adding PHPDocs or something, whatever, make my IDE understand my method is actually used?

Note that I give to my "run" call, a static string, but we can imagine also this:

<?php
$a->run($_POST['whoYouAre']); //$_POST['whoYouAre'] == 'Used'
?>

Thanks a lot!

回答1:

mark used methods in phpdoc as @used example

/**
* @uses  _iAmUsed()
* @param string $whoAreYou
*/ 
public function run($whoAreYou)
{
    $methodName = '_iAm' . $whoAreYou;
    if (method_exists($this, $methodName)) {
        $this->$methodName();
    }
}


回答2:

Add a noinspection annotation above the method:

/** @noinspection PhpUnusedPrivateMethodInspection */
private function _iAmUsed()
{
    //Do Stuff...
}

Or after running code analysis you can right-click any inspection in the results window and choose Suppress for statement to have PHPStorm add the proper annotation itself. For more information see http://www.jetbrains.com/phpstorm/webhelp/suppressing-inspections.html