Created
September 6, 2011 11:05
-
-
Save giorgiosironi/1197279 to your computer and use it in GitHub Desktop.
Assign constructor parameters to private properties
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 | |
class AutomatedAssignmentOfConstructorParametersTest extends PHPUnit_Framework_TestCase | |
{ | |
public function testParametersAreAssignedBasingOnTheirNames() | |
{ | |
$object = new MyClass(1, 2); | |
$this->assertEquals(1, $object->getFirst()); | |
$this->assertEquals(2, $object->getSecond()); | |
} | |
} | |
class MyClass | |
{ | |
private $first; | |
private $second; | |
public function __construct($first, $second) | |
{ | |
assignConstructorParameters($this, get_defined_vars()); | |
} | |
public function getFirst() | |
{ | |
return $this->first; | |
} | |
public function getSecond() | |
{ | |
return $this->second; | |
} | |
} | |
function assignConstructorParameters($object, $constructorParameters) | |
{ | |
$class = get_class($object); | |
foreach ($constructorParameters as $name => $value) { | |
if ($name == 'this') { | |
continue; | |
} | |
$reflectionProperty = new ReflectionProperty($class, $name); | |
$reflectionProperty->setAccessible(true); | |
$reflectionProperty->setValue($object, $value); | |
$reflectionProperty->setAccessible(false); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OK, thanks for explaining.