Skip to content

Instantly share code, notes, and snippets.

@giorgiosironi
Created September 6, 2011 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giorgiosironi/1197279 to your computer and use it in GitHub Desktop.
Save giorgiosironi/1197279 to your computer and use it in GitHub Desktop.
Assign constructor parameters to private properties
<?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);
}
}
@ondrejmirtes
Copy link

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.

@giorgiosironi
Copy link
Author

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.

@ondrejmirtes
Copy link

OK, thanks for explaining.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment