1

I was using CakePHP 2.5, and wrote a timer to time CURL request.

<?php
class AppController extends Controller {
    var $started = array();
    var $elapsed = array();
    var $timer = array();

    function timerStart( $callingMethod ) {
        $this->started[ $callingMethod ] = microtime( true );
    }

    function timerEnd( $callingMethod ) {
        if ( isset( $this->started[ $callingMethod ] ) && ! empty( $this->started[ $callingMethod ] ) ) {
            $this->elapsed[ $callingMethod ] = microtime( true ) - $this->started[ $callingMethod ];
            unset( $this->started[ $callingMethod ] );
            $this->set( 'timer', $this->elapsed );
        }
    }
}
?>

<?php
class ExamplesController extends AppController {
    function index() {
        $this->timerStart( __METHOD__ );
        // some curl request execution
        $this->timerEnd( __METHOD__ );
    }
}
?>

<?php
// Later somewhere in - View::Examples::Index
if ( isset( $timer ) && ! empty( $timer ) ) {
    pr( $timer ); //print_r()
}
?>

Nevertheless, every time I call $this->timerStart() I will have to provide the same parameter __METHOD__.

It would be nice if the function declaration accepts something like function timerStart( $callingMethod = __METHOD__ ), but the magic constant just won't work this way.

My question is, is there a way to achieve the same result? So that I can just call $this->timerStart() without repeating the same parameter every time.

Justin Moh
  • 1,450
  • 3
  • 14
  • 21
  • 2
    This has already beed answered [here][1] [1]: http://stackoverflow.com/questions/190421/caller-function-in-php-5/190426#190426 – Jim Wright Jul 16 '15 at 06:56
  • Indeed. `$trace = debug_backtrace();` `$caller = $trace[1]['class'] . '::' . $trace[1]['function'];` – Justin Moh Jul 16 '15 at 08:23

0 Answers0