Search code examples
phprefactoringphpstorm

Is there a way to reference a method name


When using a framework, it's often the case that you can somehow reference a class name in a configuration - often you can also reference a method.

$setting = [
    'controller' => DemoController::class,
    'action'     => 'demoAction', // how to reference this?
];

A class is referenced by ::class. The big advantage comes when it comes to refactoring because a reference can be better refactored than a simple "string".

But if you want to apply the whole thing to methods, the question arises, how can you reference a method in such a way that the same possibility arises.

Is there already a corresponding approach or even a solution for this?

i.e. -> when using a "reference" for a class - and this class will be declared as "deprecated" then each usage of this class will be marked with a stroke:

enter image description here

The same behavior is missing wenn you only use a string. This is my point. the reference via string is no "real" reference.

RFC: https://wiki.php.net/rfc/function_referencing


Solution

  • Yes, you can reference methods. Thanks to uniform variable syntax, a method call can be declared as array:

    $func = [$this, 'functionname'];
    

    Now it is bound to the current instance and can be called as

    $func();
    

    Note

    Instead of passing new DemoController() you could pass an already created instance.

    Example

    Porting this to your code would end up in:

    class DemoController {
        public function demoAction() {
            echo "Hello from DemoAction";
        }
    }
    
    $setting = [
        'controller' => DemoController::class,
        'action'     => [new DemoController(), 'demoAction'],
    ];
    
    $setting['action']();
    

    prints

    Hello from DemoAction