0

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

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

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

并在其中检查当前用户是否有权访问list_user_dataclass中的方法User

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

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

这可能吗?

4

1 回答 1

1

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();
于 2019-08-05T23:06:30.803 回答