Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you get a method name from within a method in PHP?

Tags:

methods

oop

php

Is it possible to do something like this?

public function something() {     $thisMethodName = method_get_name();  } 

Where method_get_name() returns the method's name?

like image 369
alex Avatar asked Sep 15 '09 02:09

alex


People also ask

How to get the function name inside a function in PHP?

To get the function name inside the PHP function we need to use Magic constants(__FUNCTION__). Magic constants: Magic constants are the predefined constants in PHP which is used on the basis of their use. These constants are starts and end with a double underscore (__).

What is __ method __ in PHP?

"Method" is basically just the name for a function within a class (or class function). Therefore __METHOD__ consists of the class name and the function name called ( dog::name ), while __FUNCTION__ only gives you the name of the function without any reference to the class it might be in.

What is function name in PHP?

Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$ . Tip. See also the Userland Naming Guide.

How do you call a method in PHP?

To invoke a method on an object, you simply call the object name followed by "->" and then call the method. Since it's a statement, you close it with a semicolon. When you are dealing with objects in PHP, the "->" is almost always used to access that object, whether it's a property or to call a method.


2 Answers

Sure, you want the magic constants.

function myFunction() { print __FUNCTION__." in ".__FILE__." at ".__LINE__."\n"; } 

Find out more from the php manual

like image 199
Kevin Vaughan Avatar answered Oct 06 '22 15:10

Kevin Vaughan


While you can use the magic constant __METHOD__ I would highly recommend checking out PHP's reflection. This is supported in PHP5.

$modelReflector = new ReflectionClass(__CLASS__); $method = $modelReflector->getMethod(__METHOD__); 

You can then do kick-ass stuff like inspect the signature, etc.

like image 38
thesmart Avatar answered Oct 06 '22 15:10

thesmart