How can I dereference a constructor?

Ideally, I would like to do something like this ....

$formElement->addValidator ( (new RegexValidator('/[az]/') )->setErrorMessage('Error') // setErrorMessage() returns $this ); 

Of course, PHP will not allow this, so I agree to this ...

 $formElement->addValidator ( RegexValidator::create('/[az]/')->setErrorMessage('Error') ); 

And the code in the base class ....

 static public function create( $value ) { return new static( $value ); } 

I would like to take one more step and do something like this ...

 static public function create() { return call_user_func_array( 'static::__construct', func_get_args() ); } 

Again, PHP won't let me do this. I could code individual "create" methods for each validator, but I want it to be a little smoother.

Any suggestions please?

+4
source share
2 answers

Use ReflectionClass::newInstanceArgs from the reflection API :

 $class = new ReflectionClass(__CLASS__); return $class->newInstanceArgs($args); 
+8
source
Korzin massively pointed me in the right direction, Reflection - (thanks to Krzysztof).

Note that the last static binding applies, which is only a PHP function > = 5.3

The proposed Validator :: create () method. It provides work due to the inability to call methods on objects that were created ine (see My initial question).

Base class ...

 class Validator { .... static public function create() { $class = new ReflectionClass( get_called_class() ); return $class->newInstanceArgs( func_get_args() ); } public function setErrorMessage( $message ) { .... } 

Advanced class ....

 class RegexValidator extends Validator { public function __construct( $regex ) { .... } 

Usage example ...

  $form ->getElement('slug') ->setLabel( 'Slug' ) ->addValidator( RegexValidator::create('/[az]/')->setErrorMessage('Error') ) ->addValidator( RequiredValidator::create() ); 
+9
source

All Articles