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

前端 未结 8 1872
离开以前
离开以前 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条回答
  •  萌比男神i
    2020-12-15 19:03

    The first question you should ask is, if you need to access it from outside the class, why did you declare it private? If it's not your code, the originator probably had a good reason to declare it private, and accessing it directly is a very bad (and largely unmaintainable) practice.

    EDIT: As Adam V. points out in the comments, you need to make the private method accessible before invoking it. Code sample updated to include this. I haven't tested it, though - just adding here to keep the answer updated.

    That having been said, you can use Reflection to accomplish this. Instantiate ReflectionClass, call getMethod for the method you want to invoke, and then call invoke on the returned ReflectionMethod.

    A code sample (though I haven't tested it, so there may be errors) might look like

    $demo = new Demo();
    $reflection_class = new ReflectionClass("Demo");
    $reflection_method = $reflection_class->getMethod("myPrivateMethod");
    $reflection_method->setAccessible(true);
    $result = $reflection_method->invoke($demo, NULL);
    

提交回复
热议问题