Is it possible to call a namespace using a variable?
For example:
$class_name = strtolower( $interface_name );
$return['html'] = \interfaces\$class_name::get_loginForm();
However, this returns the error:
Parse error: syntax error, unexpected '$class_name' (T_VARIABLE), expecting identifier (T_STRING)
I am connecting to several 3rd party API's which all do the same thing, but in their own unique way. The user will already be connected to their preferred API before joining our site. The middleware for the different API's will be stored within bespoke files under the same namespace.
It would be possible to solve the problem running a switch on the interface name and calling the relevant namespace, however that would mean having to locate and add to the switch(es) every time a new API comes out so any help with this problem would be appreciated. Cheers.
You can run it like this:
here is a test code and the live demo
<?php
namespace App\animal;
$animal = 'animal';
class dog{
function __construct()
{
echo __METHOD__,"\n";
}
public function data(){return 'dog';}
static function cat(){return 'cat';}
}
$name = '\App\\'.$animal.'\\dog';
$dog = new $name;
echo $dog->data();
echo "\n";
echo $name::cat();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With