Last active
October 23, 2019 19:01
-
-
Save andyvanee/3b64b22177be4321baf3c4a6e6463974 to your computer and use it in GitHub Desktop.
Demonstrating how to assign to private class members in PHP (not recommended)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class SomeClass { | |
private $priv; | |
public $pub; | |
} | |
// This function demonstrates how to access and assign to private | |
// or undeclared class members using Closure::bindTo | |
function assignPrivate($obj, $key, $value) { | |
$fn = function($k, $v) { | |
$this->$k = $v; | |
}; | |
$boundFn = $fn->bindTo($obj, $obj); | |
$boundFn($key, $value); | |
return $obj; | |
} | |
$o = new SomeClass; | |
$o->pub = 'a'; | |
assignPrivate($o, 'priv', 'b'); | |
assignPrivate($o, 'undeclared', 'c'); | |
$expected = 'SomeClass Object | |
( | |
[priv:SomeClass:private] => b | |
[pub] => a | |
[undeclared] => c | |
) | |
'; | |
assert(print_r($o, true) == $expected); | |
print_r($o); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment