'Using variable with string for new class initialization

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..



Solution 1:[1]

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();

Solution 2:[2]

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

Regards

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fenikkusu
Solution 2 chelipf