0

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

Solrac
  • 924
  • 8
  • 23

2 Answers2

0

You should try the __FUNCTION__ I guess __METHOD__ will return class name along with the function name.

  • `__FUNCTION__` will return `private_function` instead of the called method which is `my_class::my_method` – Solrac Nov 16 '15 at 07:25
0

__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;
    }
}
Luca Rainone
  • 16,138
  • 2
  • 38
  • 52
  • In my mind __METHOD__ had the value of the public function but I got it all wrong... Thanks @chumkiu I think I need some sleep :P – Solrac Nov 16 '15 at 07:58
  • would it be better to use `debug_backtrace` to get the caller method name ,so every time `private_function` is used, we dont need to add the second arg to the caller, and only need to focus on `private_function` ?? just my humble opinion – Andrew Nov 16 '15 at 08:45
  • it's never a good idea to use a function with prefix `debug` in not development environment :). The cleaner way is to pass to the function all it need to do its work. It should be also more explicative of a function name by the way. – Luca Rainone Nov 16 '15 at 08:56