Getting a child class name without namespaces

This quick code snippet allows you to retrieve the class name from within the code of the parent when you're using namespaces in your code.

There are already several useful PHP options available such as using __CLASS__ which will return the class name of an object for a parent. You can also retrieve the class name of a child object (i.e. the object that was actually instantiated) by using PHP's get_called_class() (available as of 5).Unfortunately this also brings back the namespace of class which you may not need.

So combining the above function with an explode on the slashes, here's a short and simple code snippet to get the child class from within the parent without the namespaces (note that the slash is escaped thus two slashes within the explode).

$childClassName = end(explode('\\', get_called_class()));

 

Sign Up
comments powered by Disqus
Sign Up

Popular Tags

350x250

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.