如何在变量类上调用静态方法? [英] How can I call a static method on a variable class?
问题描述
我试图做某种函数从一个给定的变量加载和实例化一个类。类似这样的:
I'm trying to make some kind of function that loads and instantiates a class from a given variable. Something like this:
<?php
function loadClass($class) {
$sClassPath = SYSPATH."/classes/{$class}.php";
if (file_exists($sClassPath)) {
require_once($sClassPath);
$class = $class::getInstance();
}
}
?>
如果我这样使用:
<?php
loadClass('session');
?>
它应该包含并实例化会话类。
It should include and instantiate the session class.
BTW:静态getInstance函数来自此代码:
BTW: the static getInstance function comes from this code:
<?php
function getCallingClass() {
$backtrace = debug_backtrace();
$method = $backtrace[1]['function'];
$file = file($backtrace[1]['file']);
$line = $file[($backtrace[1]['line'] - 1)];
$class = trim(preg_replace("/^.+?([A-Za-z0-9_]*)::{$method}\(.*$/s", "\\1\\2", $line));
if(! class_exists($class)) {
return false;
} return $class;
}
class Core {
protected static $instances = array();
public static function getInstance() {
$class = getCallingClass();
if (!isset(self::$instances[$class])) {
self::$instances[$class] = new $class();
} return self::$instances[$class];
}
}
?>
现在,在类中使用函数的方法是:
The thing is that right now the way to use the functions in a class is this:
<?php
$session = session::getInstance();
?>
但现在我想把它构建成一个函数,所以我再也不必使用那行代码。
我只是说loadClass('session');
,我可以使用$ session-> blablablafunction();
But now I want to build that into a function so that I never again have to use that line of code. I just say loadClass('session'); and than I can use $session->blablablafunction();
推荐答案
您可以使用 call_user_func()
:
You can use call_user_func()
:
$class = call_user_func(array($class, 'getInstance'));
第一个参数是 callback
type包含类名和方法名称这种情况。
The first argument is a callback
type containing the classname and method name in this case.
这篇关于如何在变量类上调用静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!