Skip to content

Instantly share code, notes, and snippets.

@Danack
Created September 23, 2013 17:33
Show Gist options
  • Save Danack/6674124 to your computer and use it in GitHub Desktop.
Save Danack/6674124 to your computer and use it in GitHub Desktop.
An example of using reflection to avoid typing.
<?php
trait Auto{
function auto($args) {
$reflectionClass = new ReflectionClass($this);
$reflectionMethod = $reflectionClass->getMethod ('__construct');
$parameters = $reflectionMethod->getParameters();
$count = 0;
foreach($parameters as $parameter) {
$paramName = $parameter->getName();
if ($reflectionClass->hasProperty($paramName) == true) {
$this->{$paramName} = $args[$count];
}
$count++;
}
}
}
class TestClass {
use Auto;
private $foo;
private $bar;
function __construct($foo, $bar) {
$args = func_get_args();
$this->auto($args);
}
function getFoo() {
return $this->foo;
}
function getBar() {
return $this->bar;
}
}
$test = new TestClass("Hello", "World!");
echo $test->getFoo().' '.$test->getBar();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment