rawilk's avatar
Level 47

Get PHP class namespace from string

I'm not sure if I'm looking in the wrong places or what, but all I can find are ways to get the class name from a string using something like class_basename(). This is the opposite of what I want; I'm looking to get the namespace from it instead.

For example, if I had the string App\Http\Controllers\Controller, I want to get the App\Http\Controllers part from the string. Of course I could explode on the \ character and just remove the last element from the array, but I am hoping to find something with similar functionality to class_basename but for the namespace instead.

0 likes
7 replies
NickVahalik's avatar
Level 8

Your best bet here is to do exactly what you just described:

function class_basename($class) {
    return join(array_slice(explode("\\", $class), 0, -1), "\\");
}
rawilk's avatar
Level 47

@casnv18 - Thanks for the reply. I kind of figured that would be the case unfortunately and you've confirmed that for me.

1 like
rawilk's avatar
Level 47

@Cronix - Would this work for any string or does the class need to exist in the application?

1 like
Cronix's avatar

Any string

$class = new \ReflectionClass('A\\B\\Foo');
echo $class->getNamespaceName();

// "A\B"

Hmm forum is escaping the \, but they should be double A\\B\\Foo, it returns A\B though

2 likes
rawilk's avatar
Level 47

@Cronix - I don't think it's going to work (unless I'm doing it wrong). If I do it on a plain string I get a ReflectionException because the class doesn't exist.

Perhaps I should have specified my use case before. My use case is I'm generating a class with an artisan command, and I need to get the namespace part of the class to append to the default namespace. For example, one type of class I'm generating is a repository, which I have the directory set to Repositories.

Here is an example of the command usage: php artisan make:repository Backend/ProductRepository

I need to be able to extract the Backend part of the string so my generated namespace will get set to Repositories\Backend in the stub file. Since the class doesn't exist, reflection isn't working for me, but a slight modification of the selected answer's code above does.

1 like
Grelav's avatar

In general if you are inside a class, you can use

__NAMESPACE__ //  constant to get the name of the class name space you are in.

Example

namespace App\Models\Artical\Category;

class YourClassNameHere extends Model
{
    function getMyNameSpace()
    {
        return __NAMESPACE__; //  returns App\Models\Artical\Category;
    }
}
1 like

Please or to participate in this conversation.