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

前端 未结 8 1865
离开以前
离开以前 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 19:13

    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);
    }
    
    0 讨论(0)
  • 2020-12-15 19:14

    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
    
    0 讨论(0)
提交回复
热议问题