Call private methods and private properties from outside a class in PHP

前端 未结 8 1863
离开以前
离开以前 2020-12-15 18:21

I want to access private methods and variables from outside the classes in very rare specific cases.

I\'ve seen that this is not be possible although introspection

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 18:54

    Just make the method public. But if you want to get tricky you can try this (PHP 5.3):

    class LockedGate
    {
        private function open()
        {
            return 'how did you get in here?!!';
        }
    }
    
    $object = new LockedGate();
    $reflector = new ReflectionObject($object);
    $method = $reflector->getMethod('open');
    $method->setAccessible(true);
    echo $method->invoke($object);
    

提交回复
热议问题