Skip to content

Instantly share code, notes, and snippets.

@andyvanee
Last active October 23, 2019 19:01
Show Gist options
  • Save andyvanee/3b64b22177be4321baf3c4a6e6463974 to your computer and use it in GitHub Desktop.
Save andyvanee/3b64b22177be4321baf3c4a6e6463974 to your computer and use it in GitHub Desktop.
Demonstrating how to assign to private class members in PHP (not recommended)
<?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