PHP __METHOD__ magic constant作为默认参数值

时间:2015-07-16 06:43:21

标签: php cakephp cakephp-2.0 cakephp-2.5

我正在使用CakePHP 2.5,并写了一个计时器来计算CURL请求。

<?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()
}
?>

尽管如此,每次拨打$this->timerStart()时,我都必须提供相同的参数__METHOD__

如果函数声明接受function timerStart( $callingMethod = __METHOD__ )之类的东西会很好,但魔术常量不会以这种方式工作。

我的问题是,有没有办法达到同样的效果?这样我每次都可以调用$this->timerStart()而不重复相同的参数。

0 个答案:

没有答案