Back (Current repo: scraps)

random scraps and notes that are useful to me
To clone this repository:
git clone https://git.viktor1993.net/scraps.git
Log | Download | Files | Refs

call_private_function_outside_class.php (1132B)


<?php

/*
 * How to access private properties and/or methods from outside the class <- without changing the class itself!
 * Why? Sometimes you might be given a framework where changing the class isn't ideal, because a version update
 * will overwrite your customizations of said class.
 *
 * How? Using Closure::call() temporarily binds $this to an instance of an object, giving the closure a
 * privileged access to the private members.
 *
 */

class Foo {
    private $bar = "Foo and Bar";
    private function add($a, $b) {
        $this->c = $a + $b;
        return $this->c;
        //return $a + $b;
    }
}

$foo = new Foo;

// Single variable example
// This should not work!
$getFooBar = function() {
    return $this->bar;
};

// now $this is bound to $foo and PHP lets the closure access the private stuff
// because now it treats it as if it were inside the class at that moment, but it isn't
echo $getFooBar->call($foo); // Prints Foo and Bar
echo PHP_EOL;

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

echo $doAdd->call($foo, 10, 5);
echo PHP_EOL;

?>