note 115411 deleted from reflectionclass.newinstance by salathe
| From: | salathe@php.net | Date: | Mon, 21 Jul 2014 07:53:42 +0000 |
| Subject: | note 115411 deleted from reflectionclass.newinstance by salathe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-199988@lists.php.net to get a copy of this message | ||
Note Submitter: talisson dot unipac at gmail dot com
----
I sometimes uses it in abstract factory pattern. Defined a default class in file .ini.
A simple example below:
//file A.php
Class A
{
private $text;
public function __construct($text)
{
$this->text = $text;
}
public print()
{
echo $this->foo, PHP_EOL;
}
}
//file Factory.php
class Factory
{
private $Class = 'A'; //This variable could be dynamic.
public function __construct() { }
public function make( $param )
{
$reflector = new reflectionClass( $this->Class );
return $reflector->newInstanceArgs( $param );
}
}
$factory = new Factory();
$B = $factory->make("Good");
$C = $factory->make("Bad");
$B->print(); //Good
$C->print(); //Bad