如何获取调用类的名称(在PHP中)

时间:2010-09-01 18:15:21

标签: php class abstraction abstract

define('anActionType', 1);
$actionTypes = array(anActionType => 'anActionType');
class core {
    public $callbacks = array();
    public $plugins = array();
    public function __construct() {
        $this->plugins[] = new admin();
        $this->plugins[] = new client();
    }
}
abstract class plugin {
    public function registerCallback($callbackMethod, $onAction) {
        if (!isset($this->callbacks[$onAction]))
            $this->callbacks[$onAction] = array();

        global $actionTypes;
        echo "Calling $callbackMethod in $callbacksClass because we got {$actionTypes[$onAction]}" . PHP_EOL;

        // How do I get $callbacksClass?

        $this->callbacks[$onAction][] = $callbackMethod;
    }
}
class admin extends plugin {
    public function __construct() {
        $this->registerCallback('onTiny', anActionType);
    }
    public function onTiny() { echo 'tinyAdmin'; }
}
class client extends plugin {
    public function __construct() {
        $this->registerCallback('onTiny', anActionType);
    }
    public function onTiny() { echo 'tinyClient'; }
}
$o = new core();

$callbacksClass应该是管理员或客户。或者我完全忽略了这一点,应该采取另一种方式吗?应该注意的是,我只接受一个不要求我将classname作为参数发送到registerCallback方法的答案。

3 个答案:

答案 0 :(得分:56)

如果有人来这里寻找如何从我这样的其他课程中获取通话类的名称,请查看https://gist.github.com/1122679

编辑:粘贴代码

function get_calling_class() {

    //get the trace
    $trace = debug_backtrace();

    // Get the class that is asking for who awoke it
    $class = $trace[1]['class'];

    // +1 to i cos we have to account for calling this function
    for ( $i=1; $i<count( $trace ); $i++ ) {
        if ( isset( $trace[$i] ) ) // is it set?
             if ( $class != $trace[$i]['class'] ) // is it a different class
                 return $trace[$i]['class'];
    }
}

<强> EG

class A {
    function t() {
        echo get_calling_class();
    }
}

class B {
    function x() {
        $a = new A;
        $a->t();
    }
}

$b = new B;
$b->x(); // prints B

答案 1 :(得分:17)

使用get_class()

$this->callbacks[$onAction][] = $callbackMethod;
$className = get_class($this);

// Call callback method
$className->$callbackMethod();

答案 2 :(得分:4)

你应该做的事情如下:

$this->registerCallback(array($this, 'onTiny'), anActionType);

这就是PHP如何处理对象方法的句柄。