PHP 魔术常量 - 自动传递给函数?

我编写了一个简单的访问控制系统,它读取一组访问字符串,并根据结果返回 true 或 false。

我会这样称呼它(例如在list_user_data类的方法中User):`

if (current_user_can(__CLASS__, __METHOD__)) { 
    ... 
    }

在里面,它检查当前用户是否有权访问list_user_dataclass 中的方法User

它有效,但我觉得很烦人,我总是必须在通话中指定__CLASS____METHOD__。有没有办法调用函数的current_user_can函数中获取这些值以便我可以简单地调用而不必传递魔术常量?current_user_can()

我的代码按原样工作,但我认为它可以改进。

这可能吗?


波斯汪
浏览 131回答 1
1回答

qq_笑_17

debug_backtrace的返回值应该返回第二个条目(索引 1)中的调用函数,例如:<?phpfunction current_user_can(){&nbsp; &nbsp; $backtrace = debug_backtrace(false, 2);&nbsp; &nbsp; // ToDo: Check if $backtrace[1] (and especially the class-key of that) actually exist...&nbsp; &nbsp; //&nbsp; &nbsp; &nbsp; &nbsp;It should always (although the class key might not if this function isn't called from within a class), since this function is being called&nbsp; &nbsp; //&nbsp; &nbsp; &nbsp; &nbsp;but it's still a good habbit to check array keys before accessing the array&nbsp; &nbsp; $callerClass = $backtrace[1]["class"];&nbsp; &nbsp; $callerMethod = $backtrace[1]["function"];&nbsp; &nbsp; // ToDo: implementation of check, in this example $callerClass would be "User" and $callerMethod would be "list_user_data"&nbsp; &nbsp; return true;}class User {&nbsp; &nbsp; public function list_user_data() {&nbsp; &nbsp; &nbsp; &nbsp; if (current_user_can())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}$user = new User();$user->list_user_data();
打开App,查看更多内容
随时随地看视频慕课网APP