PHP 自动传递给函数?



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

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

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

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

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

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

这可能吗?

来自 debug_backtrace 的返回值应返回第二个条目(索引 1)中的调用函数,例如:

<?php
function current_user_can()
{
$backtrace = debug_backtrace(false, 2);
// ToDo: Check if $backtrace[1] (and especially the class-key of that) actually exist...
//       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
//       but it's still a good habbit to check array keys before accessing the array
$callerClass = $backtrace[1]["class"];
$callerMethod = $backtrace[1]["function"];
// ToDo: implementation of check, in this example $callerClass would be "User" and $callerMethod would be "list_user_data"
return true;
}
class User {
public function list_user_data() {
if (current_user_can())
{
}
}
}
$user = new User();
$user->list_user_data();

最新更新