通过变量访问类静态函数 [英] Access class static function via variable

查看:94
本文介绍了通过变量访问类静态函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个名为router的PHP类,它使用URL并将其爆炸以找到所需的组件,操作和任何给定的值.然后,它加载负责的类,运行操作等.我现在通过一个用户类将用户访问权限集成到该类中.

So I have a PHP class called router that takes the URL and explodes it to find the requested component, action and any given values. It then loads the responsible class, runs the action, etc, etc. I am now integrationg user access into the class via an user class.

对于每个组件(是一个类),我都有一个名为"perms"的静态类数组变量,该变量将每个操作作为索引保存,并将数字作为运行该操作所需的最低权限.每个组件还具有一个静态函数,用于获取所传递动作名称的权限值.

For each component (which is a class), I have a static class array variable called 'perms' that holds each action as an index and a number as the minimum permission needed to run the action. Each component also has a static function to get the permission value for the passed action name.

我遇到的问题是使静态函数与存储在变量中的类的名称一起正常工作.在路由器中,我使用一个变量来保存组件的名称.

The problem I am having is getting the static function to work correctly with the name of the class stored in a variable. In the router I use a variable to hold the name of the component.

$this->controller // cms, calendar ,etc

然后我将'Controller'添加到其中以获得类的名称

I then add 'Controller' to it to get the name of the class

$class = $this->controller.'Controller'; // cmsController, calendarController, etc

但是,当我尝试使用它访问静态函数时出现错误

However, I am getting an error when I try to use it to access the static function

$minActionPerm = $class::getPerms( $this->action ); // No go, parse error

从字面上键入类名时不会出现任何错误,但这不是真正的解决方案.

I get no error when I literally type in the class name, but this is not a real solution.

$minActionPerm = cmsController::getPerms( $this->action ); // Good, but literal

当我创建类的对象以执行操作时,该变量也起作用.

The variable also works when I create an object of the class to run the action.

$object = new $class();

我确定这可能只是一个简单的答案-例如变量使用,但这是我目前尚不知道的答案.

I'm sure it is probably just a simple answer - such as variable use, but it's one I don't know as of right now.

推荐答案

您需要使用

You need to use the call_user_func function.

示例:

call_user_func(array($class, 'getPerms'), $this->action);

如果您使用的是PHP 5.2.3+,也可以通过以下方式进行操作:

If you are using PHP 5.2.3+ you can also do it this way:

call_user_func($class . '::getPerms', $this->action);

这篇关于通过变量访问类静态函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆