Home > Blockchain >  Using variable with string for new class initialization
Using variable with string for new class initialization

Time:04-04

I need to initialize new class Safe with constructor call.

The way it works:

$paymentPortal = new Safe($order);

The way it doesnt:

$portal = 'Safe';
$paymentPortal = new $portal($order);

I get error:

PHP Fatal error:  Uncaught Error: Class 'Safe' not found in ...

Is there a way to dynamically call class initialization? If it is important, I'm using Phalcon framework..

CodePudding user response:

What about the namespace? if you are using an IDE it may have deleted the namespace. Check that.

Regards

CodePudding user response:

When using string based creation, you must use the fully qualified namespace of the class regardless of the local namespace.

use My\Stuff;
$o = new Stuff();
$name = ‘My\Stuff’;
$o = new $name();
$name = Stuff::class;
$o = new $name();
  • Related