Search code examples
phpclassmagic-constants

Unable to compare magic constant __METHOD__


Ok, I think I have something here...

Inside a class, im trying to condition a private function based on the used method's name.

So the code looks something like:

<?php
class my_class{

 public function my_method($arg1) {
  $this->private_function($arg1);
 }

 private function private_function($arg2){
  if (__METHOD__ == "my_class::my_method"){
    #THIS FAILS
  }else{
    #THIS WORKS
  }
  return;
 }
}

(new my_class())->my_method($something);

If I do a var_dump() on __METHOD__ at the same level im trying to use it I'll get a nice string(19)"my_class::my_method". So I'm comparing a string to another one.

The following will also fail:

  • Cast both vars to string and compare them.
  • Copy __METHOD__ to a (string) $var and compare them.
  • Upper both strings and compare them.
  • Using single quotes for the text.

I might be wrong but I think I hit a bug here :(

PHP Version 5.6.1 - Win


Solution

  • __METHOD__ returns the current class method name. In your case this is my_class::private_function.

    If you want to know the caller method, the cleanest way is to pass it as argument.

    class my_class {
    
        public function my_method($arg1) {
            $this->private_function($arg1, __METHOD__);
        }
    
        private function private_function($arg2, $caller) {
            if ($caller == "my_class::my_method") {
    
            } else {
    
            }
            return;
        }
    }