Last active
April 26, 2024 13:24
-
-
Save samsamm777/7230159 to your computer and use it in GitHub Desktop.
PHP set private property value using reflection. This allows you to set a private property value from outside the object, great for PHPUnit testing.
This file contains 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 | |
$a = new A(); | |
$reflection = new \ReflectionClass($a); | |
$property = $reflection->getProperty('privateProperty'); | |
$property->setAccessible(true); | |
$property->setValue($a, 'new-value'); | |
echo $a->getPrivateProperty(); | |
//outputs: | |
//new-value |
You can use readAttribute easier
You can also use a closure binding:
class A {
private string $name;
}
$a = new A();
$setter = (function (string $property, mixed $value): void {
$this->{$property} = $value;
})->bindTo($a, $a);
$setter('name', 'Name');
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Along similar lines, this trait will let you copy similar properties from one class to another.
In your class just add:
then you can
$a = new A();
$b = $a->to('B');