Core\Reflect\MethodInfo::name
$methodInfo->name(): stringReturns the name of one method of a class.
name() returns the name that the class declares, such as send or total. The name has no class name and no parentheses. The constructor of a class is named constructor. A class also lists the methods it inherits from its parent class.
You can pass the name to Core\Reflect\ClassInfo::hasMethod to check that a method exists. You can pass it to Core\Reflect\ClassInfo::call to call the method. Names are case-sensitive, so Send does not find send.
The examples below print the methods of a class, show the methods a class inherits, and run a command whose name a user typed.
Return value
Returns string. The name as the class declares it, with no class name and no parentheses. A constructor is named constructor. You can pass the name to Core\Reflect\ClassInfo::hasMethod and Core\Reflect\ClassInfo::call.
Examples
Print the method names
<?nvs// Shows how to print the name of every method of a class.
class Invoice{ public function constructor(public int $net) {}
public function total(): int { return $this->net + $this->shipping(); }
private function shipping(): int { return 5; }}
// `methods` returns the methods sorted by name.// This prints `constructor`, `shipping` and `total`.foreach (Core\Reflect::forObject(new Invoice(100))->methods() as Core\Reflect\MethodInfo $method) { echo $method->name(), "\n";}constructorshippingtotalMethods from the parent class
<?nvs// Shows that a class also lists the methods it inherits from its parent class.
class Shape{ public function describe(): string { return 'a shape'; }}
class Square extends Shape{ public function area(int $side): int { return $side * $side; }}
// `Square` declares only `area`. It also inherits `describe` from `Shape`.// This prints `area` and `describe`.foreach (Core\Reflect::forObject(new Square())->methods() as Core\Reflect\MethodInfo $method) { echo $method->name(), "\n";}areadescribeRun a command a user typed
<?nvs// Shows how a command-line tool runs the command a user typed, and lists the commands when the name is wrong.
class Commands{ public function status(): string { return 'All services are running.'; }
public function version(): string { return 'Version 2.4.1'; }}
class Tool{ public static function run(string $typed): void { var $commands = new Commands(); var $info = Core\Reflect::forObject($commands); if ($info->hasMethod($typed)) { echo $info->call($commands, $typed, []) as string, "\n"; return; } // The name is not a command, so the tool prints the names that are. echo "Unknown command '", $typed, "'. Try one of:"; foreach ($info->methods() as Core\Reflect\MethodInfo $method) { echo ' ', $method->name(); } echo "\n"; }}
Tool::run('version');// Names are case-sensitive, so `Status` is not a command.Tool::run('Status');Version 2.4.1Unknown command 'Status'. Try one of: status version