nks
nks

Reputation: 123

Create object with variable class name and namespace

I am trying to create an object with a parameter to loader function while using shorten namespace path in it. It goes like,

    use Com\Core\Service\Impl as Impl;

    class Load {
        public static function service(String $class, array $params = array()){
            try {
                $ucfirstclass = ucfirst($class);
                if (interface_exists('\\Com\\Core\\Service\\' . $ucfirstclass)) {
                    $ref = "Impl\\".$ucfirstclass;
                    return new $ref();
                } else {
                    throw new Exception("Service with name $class not found");
                }
            } catch (\Throwable $ex) {
                echo $ex->getMessage();
            }
        }
    }

While calling it like,

    $userService = Load::service("user"); 

it is throwing an exception

    Class 'Impl\User' not found

Though it'll work fine if I'll just replace "Impl" inside Load::service() implementation with full path "Com\Core\Service\Impl".

I'm new with this. Can someone help here why can't I use shorten path "Com\Core\Service\Impl as Impl" ?

Upvotes: 1

Views: 1398

Answers (2)

axiac
axiac

Reputation: 72425

while using shorten namespace path in it.

There is no such thing as "short namespace". A namespace or a class is determined by its complete path, starting from the root namespace.

use Com\Core\Service\Impl as Impl;

Impl in the above fragment of code is a class or namespace alias. An alias is resolved at the compile time and it is valid only in the file where it is declared.

It is not possible to use an alias during the runtime. The only way to refer to a class name during runtime is to generate its absolute path (starting from the root namespace).
You already discovered this.

Read more about namespace aliases/importing.

Upvotes: 2

localheinz
localheinz

Reputation: 9592

When referring to class names as strings, you always have to use the fully-qualified class name.

Try this:

$ucfirstclass = ucfirst($class);

if (interface_exists('Com\\Core\\Service\\' . $ucfirstclass)) {
    $ref = 'Com\\Core\\Service\\Impl\\' .$ucfirstclass;

    return new $ref();
}

For reference, see:

Upvotes: 1

Related Questions