joe92
joe92

Reputation: 643

PHP Using variable to call namespace

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.

Upvotes: 3

Views: 2848

Answers (2)

user1037355
user1037355

Reputation:

The answer from @Kris Roofe should work but i would approach it differently with the call_user_func_array function http://php.net/manual/de/function.call-user-func-array.php

Example:

call_user_func_array( $function_as_string.'::'.$method_as_string, $params );

Where $params is an array of data that will be passed to the said function as method params.

So in your example it would be

call_user_func_array('\\interfaces\\'.$class_name.'::get_loginForm');

Upvotes: 2

LF-DevJourney
LF-DevJourney

Reputation: 28529

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

Upvotes: 5

Related Questions