Re: Keyword Constructor
| From: | Richard Quadling | Date: | Tue, 02 Aug 2011 12:30:14 +0000 |
| Subject: | Re: Keyword Constructor | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-314272@lists.php.net to get a copy of this message | ||
On 2 August 2011 06:28, Ren <lobbyjones@gmail.com> wrote:
> For a long time I wanted keyword parameters in PHP. But thanks to
> newer features like traits and reflection classes I have come up with
> something that looks pretty close.
>
> trait KeywordConstructor {
> public function __construct($members) {
> $class = new ReflectionClass($this);
> $properties = $class->getProperties();
>
> foreach ($properties as $p) {
> $name = $p->getName();
>
> if (isset($members[$name])) {
> $this->$name = $members[$name];
> }
> }
> }
> }
>
> class User {
> use KeywordConstructor;
> private $name;
> private $age;
> }
>
> $lobby = new User(['name' => 'Lobby', 'age' => 36]);
>
> Right now this requires the trunk version of PHP to work. I just
> wanted to share this in case anyone finds it interesting and/or
> useful.
I use a similar technique when I need to populate a SOAP class on the
server to coerce data from the DB into the appropriate type as defined
in the docblock of the class.
--
Richard Quadling
Twitter : EE : Zend : PHPDoc
@RQuadling : e-e.com/M_248814.html : bit.ly/9O8vFY : bit.ly/lFnVea