Search code examples
phpmagic-constants

PHP magic constants - automatically passed to function?


I wrote a simple access control system which reads an array of access strings, and return true or false depending on the result.

I would call it as follows (for example in a method list_user_data of class User): `

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

and inside there, it checks if the current user has permission to access method list_user_data in class User.

It works, but I find it annoying that I always have to specify __CLASS__ and __METHOD__ in the call. Is there a way to get those values from within the current_user_can function for the calling function so that I can simply call current_user_can() without having to pass the magic constants?

My code works as is, but I am thinking it could be improved.

Is this possible?


Solution

  • The return value from debug_backtrace should return the calling function in the 2nd entry (index 1), for example:

    <?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();