如何获取调用类的名称(PHP 格式)

2022-08-30 15:47:58
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应为管理员或客户端。还是我在这里完全错过了重点,应该以另一种方式进行?应该注意的是,我只接受一个不需要我将类名作为参数发送到registerCallback方法的答案。


答案 1

如果有人像我一样来到这里寻找如何从另一个类获取呼叫类的名称,请查看此 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'];
    }
}

断续器

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

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

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

答案 2

使用 get_class()

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

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

推荐