Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a protected method from outside a class in PHP

I have a very special case in which I need to call a protected method from outside a class. I am very conscious about what I do programmingwise, but I would not be entirely opposed to doing so in this one special case I have. In all other cases, I need to continue disallowing access to the internal method, and so I would like to keep the method protected.

What are some elegant ways to access a protected method outside of a class? So far, I've found this.

I suppose it may be possible create some kind of double-agent instance of the target class that would sneakily provide access to the internals...

like image 486
Chad Johnson Avatar asked Jun 11 '09 17:06

Chad Johnson


2 Answers

In PHP you can do this using Reflections. To invoke protected or private methods use the setAccessible() method http://php.net/reflectionmethod.setaccessible (just set it to TRUE)

like image 154
Maria Avatar answered Oct 01 '22 19:10

Maria


I would think that in this case, refactoring so you don't require this sort of thing is probably the most elegant way to go. In saying that one option is to use __call and within that parse debug_backtrace to see which class called the method. Then check a friends whitelst

class ProtectedClass {

    // Friend list
    private $friends = array('secret' => array('FriendClass')); 

    protected function secret($arg1, $arg2) {
        // ...
    }

    public function __call($method, $args) {

        $trace = debug_backtrace();
        $class = $trace[1]['class'];
        if(in_array($class, $this->friends[$method]))
            return $this->$method($args[0], $args[1]);

        throw new Exception();
    }
}

I think I need a shower.

like image 41
rojoca Avatar answered Oct 01 '22 18:10

rojoca