Valorin Valorin - 4 months ago 11
PHP Question

How to check if a function is public or protected in PHP

I am building an API where the user requests a 'command', which is passed into a class. Assuming the command matches a PUBLIC function, it will execute successfully.
If the command matches a PROTECTED function, it needs to throw an error.

The idea is that functions can be disabled by changing them from PUBLIC to PROTECTED, rather than renaming them or removing them.

I currently do this, but it doesn't matter if the command is public or protected.

<?php
/**
* Look for Command method
*/
$sMethod = "{$sCommand}Command";
if (method_exists($this, $sMethod))
{
/**
* Run the command
*/
return $this->$sMethod($aParameters);
}

Answer

Simply use ReflectionMethod:

/**
 * Look for Command method
 */
if (method_exists($this, $sMethod))
{
    $reflection = new ReflectionMethod($this, $sMethod);
    if (!$reflection->isPublic()) {
        throw new RuntimeException("The called method is not public.");
    }
    /**
     * Run the command
     */
    return $this->$sMethod($aParameters);
}
Comments