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 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 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); | |
} | |
} |
Please do not take this as a solution for production code - it is a proof of concept to see if such a feature build into the language (like in Scala) would make sense.
OK, thanks for explaining.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't think it's a good idea - it does not give any clue if you pass parameters of bad types to the constructor, which is helpful while using DI container.