3

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.

1
  • $return['html'] = '\\interfaces\\'.$class_name.''::get_loginForm(); Commented Sep 13, 2021 at 21:14

2 Answers 2

5

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your help! Sadly, it is returning an error still: Uncaught Error: Class 'bromcom' not found in /path/classes/Model.php:643 .... The Model is within it's own namespace which may be causing scope issues?
many thanks for your help! Works perfectly. Upvoted. The method John proposed is a little cleaner using a native PHP function so I've selected that as the accepted answer.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.