33

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 is used.

The specific case is the next one:

I would like to have something like this:

class Console
{
    final public static function run() {

        while (TRUE != FALSE) {
            echo "\n> ";
            $command = trim(fgets(STDIN));

            switch ($command) {
                case 'exit':
                case 'q':
                case 'quit':
                    echo "OK+\n";
                    return;
                default:
                    ob_start();
                    eval($command);
                    $out = ob_get_contents();
                    ob_end_clean();

                    print("Command: $command");
                    print("Output:\n$out");         

                    break;
            }
        }
    }
}

This method should be able to be injected in the code like this:

Class Demo
{
    private $a;

    final public function myMethod()
    {
        // some code
        Console::run();
        // some other code
    }

    final public function myPublicMethod()
    {
        return "I can run through eval()";
    }

    private function myPrivateMethod()
    {
        return "I cannot run through eval()";
    }
}

(this is just one simplification. the real one goes through a socket, and implement a bunch of more things...)

So...

If you instantiate the class Demo and you call $demo->myMethod(), you'll get a console: that console can access the first method writing a command like:

> $this->myPublicMethod();

But you cannot run successfully the second one:

> $this->myPrivateMethod();

Do any of you have any idea, or if there is any library for PHP that allows you to do this?

Thanks a lot!

5
  • 2
    Erm... Who would ever want to make methods tagged private publicly accessible? I mean... if you need to access it from outside, just use public. Also: Your console class makes no sense the way you added it here. It makes not a single use of OOP and is basically just a function forced into a class.
    – lamas
    Apr 29, 2010 at 15:50
  • 1
    FYI while(true) or for(;;) are slightly more succinct and common methods of looping until an explicit break or returnis encountered.
    – user229044
    Apr 29, 2010 at 16:13
  • @lamas: As I said previously, i've done this more as a POC than a real example. The real Console class has more or less about 1k lines and extends some others by composition. The maintainability of the code is not a problem since it will be used as a isolated component outside the main project we're working for, so that is not only "a function forced into a class", but a excerpt from a class that will not be posted here to avoid people getting annoyed. :) @meagar: hehe, I did the while(TRUE != FALSE) as a joke, since PHP validates FALSE != 0 as FALSE. thanks anyway ;) Apr 29, 2010 at 18:38
  • @meagar: and, i forgot to comment it, I never wrote a return nor a continue inside a function unless is a PoC. I think is not a good practice and things like that could disturb the legibility of the code. Apr 29, 2010 at 18:45
  • @lamas: I'm perfectly in line with you Re: the choice of scope. But I don't agree with you about the fact that a class would make no sense if it didn't have a single OOP call in it, and purely static functions in it: it is a way to constitute a library, and still benefit from autoloader features, or even just to make the code cleaner, and add a cataloging level for your functions. Oct 29, 2019 at 0:45

9 Answers 9

84

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);
8
  • that's exactly what I was looking for. I'm currently using PHP 5.2.3 in the dev environment, but we're in the migration process so that helps me a lot!! +1 Apr 29, 2010 at 18:40
  • @webbiedave: Hm, I also have final class LockedGate { private function __construct() {} ... } and it doesn't seem to work. I wonder if "final" prevents the accessibility from being changed. Jan 23, 2013 at 11:30
  • 4
    @webbiedave: Ahh, I think my problem may have been that it was a static class. This worked for me $method = $reflector->getMethod('myStaticPrivate'); $method->setAccessible(true); $method->invoke(NULL); Jan 23, 2013 at 11:48
  • 4
    Trying this with PHP 5.3.22 on the shell $ php -a fails with: PHP Fatal error: Call to private method LockedGate::open() from context '' in php shell code on line 1 PHP Stack trace: PHP 1. {main}() php shell code:0 Fatal error: Call to private method LockedGate::open() from context '' in php shell code on line 1 Call Stack: 5.3208 641904 1. {main}() php shell code:0 Mar 6, 2013 at 7:47
  • I've updated the reflection code. However, my primary answer still remains just make the method public.
    – webbiedave
    Oct 5, 2015 at 6:05
27

EDIT: Updated to include examples of private function calls with parameters.

As of PHP 5.4, you can use the predefined Closure class to bind a method/property of a class to a delta functions that has access even to private members.

The Closure class

For example we have a class with a private variable and we want to access it outside the class:

class Foo {
    private $bar = "Foo::Bar";
    private function add_ab($a, $b) {
        return $a + $b;
    }
}

PHP 5.4+

$foo = new Foo;

// Single variable example
$getFooBarCallback = function() {
    return $this->bar;
};

$getFooBar = $getFooBarCallback->bindTo($foo, 'Foo');

echo $getFooBar(); // Prints Foo::Bar

// Function call with parameters example
$getFooAddABCallback = function() {
    // As of PHP 5.6 we can use $this->fn(...func_get_args()) instead of call_user_func_array
    return call_user_func_array(array($this, 'add_ab'), func_get_args());
};

$getFooAddAB = $getFooAddABCallback->bindTo($foo, 'Foo');

echo $getFooAddAB(33, 6); // Prints 39

As of PHP 7, you can use the new Closure::call method, to bind any method/property of an obect to a callback function, even for private members:

PHP 7+

$foo = new Foo;

// Single variable example
$getFooBar = function() {
    return $this->bar;
};

echo $getFooBar->call($foo); // Prints Foo::Bar

// Function call with parameters example
$getFooAddAB = function() {
    return $this->add_ab(...func_get_args());
};

echo $getFooAddAB->call($foo, 33, 6); // Prints 39
6
  • 4
    PHP 7+ section is awesome! Great! May 23, 2018 at 6:08
  • @NurbolAlpysbayev thanks. I just realized that the answer does not cover a function call with parameters but only private variables! Updated and added examples for private function calls for both PHP 5.4+ and PHP 7+. May 23, 2018 at 9:16
  • This works which is great! But do you think this is best practice as they probably made it private for a reason? Jun 19, 2018 at 14:49
  • 2
    @DavidJarrin Of course it is NOT the best practise. This should be avoided if posible; it may be used when we want to have that access to that private memeber and 1) we don't want to alter the class source files (maybe a ready lib which will break after updating) and 2) if it's one of your project;s classes, then change the property/function to public, or make an other function to retreive that private member. Jun 19, 2018 at 15:05
  • @ChristosLytras yea thats the situation for me, I don't really want to alter the library because it will break on update, thanks for the response. Jun 19, 2018 at 17:58
5

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);
2
  • This should result in a ReflectionException ('Trying to invoke private method from scope ReflectionMethod').
    – webbiedave
    Apr 29, 2010 at 16:06
  • 1
    PHP Reflection API does support invoking private methods. You just need a $reflection_method->setAccessible(true) after the $reflection_method = $reflection_class->getMethod("myPrivateMethod")
    – Adam V.
    Jan 4, 2012 at 17:20
4

Here's a variation of the other answers that can be used to make such calls one line:

public function callPrivateMethod($object, $methodName)
{
    $reflectionClass = new \ReflectionClass($object);
    $reflectionMethod = $reflectionClass->getMethod($methodName);
    $reflectionMethod->setAccessible(true);

    $params = array_slice(func_get_args(), 2); //get all the parameters after $methodName
    return $reflectionMethod->invokeArgs($object, $params);
}
1

I have these problems too sometimes, however I get around it through my coding standards. Private or protected functions are denoted with a prefix underscore ie

private function _myPrivateMethod()

Then i simply make the function public.

public function _myPrivateMethod()

So although the function is public the naming convention gives the notification that whilst public is is private and shouldn't really be used.

1

If you are able to added a method in the class where the method is defined, you can add method which uses the call_user_method() internally. This works also with PHP 5.2.x

<?php
class SomeClass {
    public function callprivate($methodName) {
         call_user_method(array($this, $methodName));
    }

    private function somePrivateMethod() {
         echo 'test';
    }
}


$object = new SomeClass();
$object->callprivate('somePrivateMethod');
1

Answer is put public to the method. Whatever trick you are going to do it wouldn't be understandable to fellow developers. For example they do not know that at some other code this function has been accessed as public by looking at the Demo class.

One more thing. that console can access the first method writing a command like:. How can this even be possible? Console can not access demo class functions by using $this.

1
  • 2
    I think all the people here looking to do that are the 'fellow developers' :)
    – beppe9000
    May 10, 2019 at 20:22
0

I guess the reflectionClass is the only alternative if you really want to execute some private methods. Anyhow, if you just need read access to privat or protected properties, you could use this code:

<?php
class Demo
{
    private $foo = "bar";
}

$demo = new Demo();

// Will return an object with public, private and protected properties in public scope.
$properties = json_decode(preg_replace('/\\\\u([0-9a-f]{4})|'.get_class($demo).'/i', '', json_encode((array) $demo)));

?>
-1
<?php
$request="email";
$data=[1,2,3,4,5];
$name=new Update($request,$data);

  class Update{
      private $request;
      private $data;
      function __construct($request,$data){
          $this->request=$request;
          $this->data=$data;
          if($this->request=='email'){
            $this->update_email();
          }
          else{
              echo "Can't do anything";
          }
          
      }
      private function update_email(){
          echo $this->request;
          echo '\n';
          foreach($this->data as $x){
              echo $x."\n";
          }
      }
    }
?>
1
  • 1
    While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. You can use the edit button to improve this answer to get more votes and reputation! May 4, 2021 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.