John Davidson

PHP callback: Is there an equivalent for ::class for a method of a class?

0 comments
Message:


In PHP it is possible to get a full class name via class name resolution like this:


Example:


namespace Name\Space;
class ClassName {}

echo ClassName::class;

Output: Name\Space\ClassName


This is better than using the string Name\Space\ClassName directly in the code because code introspection especially in IDEs can find an error directly.


I wonder if there is something similar for methods of a class - this would be specifically useful for callback functions.


This is how you can basically can pass a callback:


$a = function($callback,$arg) { return $callback($arg); }

$a('getInfo',5);

Instead of passing a string here (which might change), I would prefer to do something like this:


$a(MyClass::class::getInfo,5);

With I "go to declaration" click in the IDE I could go directly to getInfo plus I see errors in case with method does not exist anymore. Is there a way to achieve what I want to do here?



My Answer:
'm afraid there is no equivalent for ::class for methods of a class in PHP. You will have to pass the method name as a string in the callback function. However, you can use the array syntax to pass a method of a class as a callback like this:

php
$a = function($callback, $arg) {
return $callback($arg);
};

$a([MyClass::class, 'getInfo'], 5);


This way, you can pass the class name and method name as an array, which is more reliable than passing a string directly.

Rate this post

4 of 5 based on 9925 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us