PHPverse 2025

Voting

: max(seven, four)?
(Example: nine)

The Note You're Voting On

me at nwhiting dot com
14 years ago
Method for pulling the name of a class with namespaces pre-stripped.

<?php
/**
* Returns the name of a class using get_class with the namespaces stripped.
* This will not work inside a class scope as get_class() a workaround for
* that is using get_class_name(get_class());
*
* @param object|string $object Object or Class Name to retrieve name

* @return string Name of class with namespaces stripped
*/
function get_class_name($object = null)
{
if (!
is_object($object) && !is_string($object)) {
return
false;
}

$class = explode('\\', (is_string($object) ? $object : get_class($object)));
return
$class[count($class) - 1];
}
?>

And for everyone for Unit Test goodiness!

<?php
namespace testme\here;

class
TestClass {

public function
test()
{
return
get_class_name(get_class());
}
}

class
GetClassNameTest extends \PHPUnit_Framework_TestCase
{
public function
testGetClassName()
{
$class = new TestClass();
$std = new \stdClass();
$this->assertEquals('TestClass', get_class_name($class));
$this->assertEquals('stdClass', get_class_name($std));
$this->assertEquals('Test', get_class_name('Test'));
$this->assertFalse(get_class_name(null));
$this->assertFalse(get_class_name(array()));
$this->assertEquals('TestClass', $class->test());
}
}
?>

<< Back to user notes page

To Top