Created
September 23, 2013 17:33
-
-
Save Danack/6674124 to your computer and use it in GitHub Desktop.
An example of using reflection to avoid typing.
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 | |
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