PHP 5.5 introduced a neat class name resolution method using the ::class
syntax. I imagine this made life easier for a lot of people. It certainly did for me.
PHP 5.5使用:: class语法引入了一个简洁的类名解析方法。我想这让很多人的生活变得更轻松。它确实对我有用。
But now I find myself having to go one step further: getting the namespace of a certain class. This isn't a hard programming task. It can be achieved with string operations or arrays:
但现在我发现自己必须更进一步:获得某个类的命名空间。这不是一项艰难的编程任务。它可以通过字符串操作或数组来实现:
$parts = explode('\\', \Foo\Bar\Baz::class);
array_pop($parts);
return implode('\\', $parts); // returns "Foo\Bar"
But this is an overkill, since I'm using this a lot (as a means to metaprogramming). It actually shows up as a bottleneck when I profile the application. Anyone got an idea for a more efficient solution?
但这是一种矫枉过正,因为我经常使用它(作为元编程的一种手段)。当我分析应用程序时,它实际上显示为瓶颈。有人想知道更有效的解决方案吗?
1 个解决方案
#1
0
At least
$class = \Foo\Bar\Baz::class;
$namespace = substr($class, 0, strrpos($class, '\\'));
should be more efficient.
应该更有效率。
#1
0
At least
$class = \Foo\Bar\Baz::class;
$namespace = substr($class, 0, strrpos($class, '\\'));
should be more efficient.
应该更有效率。