Skip to content

Instantly share code, notes, and snippets.

@Shelob9
Last active February 14, 2022 16:09
Show Gist options
  • Save Shelob9/c4921126666b0950e046 to your computer and use it in GitHub Desktop.
Save Shelob9/c4921126666b0950e046 to your computer and use it in GitHub Desktop.
Get name of class, without the namespace. get_called_class() used instead of __CLASS__ to ensure that if class is extended, that class' name is used.
<?php
$class = get_called_class();
$class = explode( '\\', $class );
end( $class );
$last = key( $class );
$class = $class[ $last ];
/**
* Get the class' name
*
* @return array|string
*/
public function get_class_name( $without_namespace = true ) {
$class = get_called_class();
if ( $without_namespace ) {
$class = explode( '\\', $class );
end( $class );
$last = key( $class );
$class = $class[ $last ];
}
return $class;
}
@cofirazak
Copy link

Why not just?
$class = get_called_class();
$class = explode( '', $class );
$class = end( $class );

@SomewhatCloudy
Copy link

Or if you want a one liner:
substr(get_called_class(), strrpos(get_called_class(), '\\') + 1);

@tupikoff
Copy link

(new \ReflectionClass(get_called_class()))->getShortName()

@miguel-serrano
Copy link

(new \ReflectionClass(get_called_class()))->getShortName()

Perfect!

@Shelob9
Copy link
Author

Shelob9 commented Jun 4, 2021

This has been one of my favorite, slow motion code reviews. Thanks y'all!

@HSken
Copy link

HSken commented Feb 14, 2022

class_basename(get_called_class())

Oeps thats a laravel helper function:

if (! function_exists('class_basename')) {
    /**
     * Get the class "basename" of the given object / class.
     *
     * @param  string|object  $class
     * @return string
     */
    function class_basename($class)
    {
        $class = is_object($class) ? get_class($class) : $class;

        return basename(str_replace('\\', '/', $class));
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment