How to Get Class Name in PHP

How do I get class name in PHP?

Since PHP 5.5 you can use class name resolution via ClassName::class.

See new features of PHP5.5.

<?php

namespace Name\Space;

class ClassName {}

echo ClassName::class;

?>

If you want to use this feature in your class method use static::class:

<?php

namespace Name\Space;

class ClassName {
/**
* @return string
*/
public function getNameOfClass()
{
return static::class;
}
}

$obj = new ClassName();
echo $obj->getNameOfClass();

?>

For older versions of PHP, you can use get_class().

Laravel get class name of related model

Yes, there is a way to get related model without query:

$className = get_class($faq->products()->getRelated());

It will work for all relations.

This will return full name with namespace. In case you want just base name use:

// laravel helper:
$baseClass = class_basename($className);

// generic solution
$reflection = new ReflectionClass($className);
$reflection->getShortName();

How do I get an object's unqualified (short) class name?

You can do this with reflection. Specifically, you can use the ReflectionClass::getShortName method, which gets the name of the class without its namespace.

First, you need to build a ReflectionClass instance, and then call the getShortName method of that instance:

$reflect = new ReflectionClass($object);
if ($reflect->getShortName() === 'Name') {
// do this
}

However, I can't imagine many circumstances where this would be desirable. If you want to require that the object is a member of a certain class, the way to test it is with instanceof. If you want a more flexible way to signal certain constraints, the way to do that is to write an interface and require that the code implement that interface. Again, the correct way to do this is with instanceof. (You can do it with ReflectionClass, but it would have much worse performance.)

Get class name of executed static function without namespace

Acquiring the class name without a namespace

Yes, you can do it using the ReflectionClass. Since your question relates to doing this from within a static method, you can get the class name like so:

$reflect = new \ReflectionClass(get_called_class());
$reflect->getShortName();

This uses the ReflectionClass constructor by passing a string with the fully namespaced name of the class to be inspected.

There is a similar question at How do I get an object's unqualified (short) class name? however it does not refer to doing this within a static method and so the examples pass an instantiated object to the ReflectionClass constructor.

Get class name from file

There are multiple possible solutions to this problem, each with their advantages and disadvantages. Here they are, it's up to know to decide which one you want.

Tokenizer

This method uses the tokenizer and reads parts of the file until it finds a class definition.

Advantages

  • Do not have to parse the file entirely
  • Fast (reads the beginning of the file only)
  • Little to no chance of false positives

Disadvantages

  • Longest solution

Code

$fp = fopen($file, 'r');
$class = $buffer = '';
$i = 0;
while (!$class) {
if (feof($fp)) break;

$buffer .= fread($fp, 512);
$tokens = token_get_all($buffer);

if (strpos($buffer, '{') === false) continue;

for (;$i<count($tokens);$i++) {
if ($tokens[$i][0] === T_CLASS) {
for ($j=$i+1;$j<count($tokens);$j++) {
if ($tokens[$j] === '{') {
$class = $tokens[$i+2][1];
}
}
}
}
}

Regular expressions

Use regular expressions to parse the beginning of the file, until a class definition is found.

Advantages

  • Do not have to parse the file entirely
  • Fast (reads the beginning of the file only)

Disadvantages

  • High chances of false positives (e.g.: echo "class Foo {";)

Code

$fp = fopen($file, 'r');
$class = $buffer = '';
$i = 0;
while (!$class) {
if (feof($fp)) break;

$buffer .= fread($fp, 512);
if (preg_match('/class\s+(\w+)(.*)?\{/', $buffer, $matches)) {
$class = $matches[1];
break;
}
}

Note: The regex can probably be improved, but no regex alone can do this perfectly.

Get list of declared classes

This method uses get_declared_classes() and look for the first class defined after an include.

Advantages

  • Shortest solution
  • No chance of false positive

Disadvantages

  • Have to load the entire file
  • Have to load the entire list of classes in memory twice
  • Have to load the class definition in memory

Code

$classes = get_declared_classes();
include 'test2.php';
$diff = array_diff(get_declared_classes(), $classes);
$class = reset($diff);

Note: You cannot simply do end() as others suggested. If the class includes another class, you will get a wrong result.


This is the Tokenizer solution, modified to include a $namespace variable containing the class namespace, if applicable:

$fp = fopen($file, 'r');
$class = $namespace = $buffer = '';
$i = 0;
while (!$class) {
if (feof($fp)) break;

$buffer .= fread($fp, 512);
$tokens = token_get_all($buffer);

if (strpos($buffer, '{') === false) continue;

for (;$i<count($tokens);$i++) {
if ($tokens[$i][0] === T_NAMESPACE) {
for ($j=$i+1;$j<count($tokens); $j++) {
if ($tokens[$j][0] === T_STRING) {
$namespace .= '\\'.$tokens[$j][1];
} else if ($tokens[$j] === '{' || $tokens[$j] === ';') {
break;
}
}
}

if ($tokens[$i][0] === T_CLASS) {
for ($j=$i+1;$j<count($tokens);$j++) {
if ($tokens[$j] === '{') {
$class = $tokens[$i+2][1];
}
}
}
}
}

Say you have this class:

namespace foo\bar {
class hello { }
}

...or the alternative syntax:

namespace foo\bar;
class hello { }

You should have the following result:

var_dump($namespace); // \foo\bar
var_dump($class); // hello

You could also use the above to detect the namespace a file declares, regardless of it containing a class or not.

How to obtain class name in a static method in PHP?

For PHP >=5.3 you can use get_called_class().

Example copied from http://php.net/get_called_class

<?php

class foo {
static public function test() {
return get_called_class();
}
}

class bar extends foo {
}

print foo::test();
print bar::test();
?>

The above example will output:

foo
bar

How to get class by name in PHP?

You can simply call the method on the variable, you might want to wrap an "if" around it to check if the class exists.

$className = "Model";
if (class_exists($className)) {
$className::sayHello();
}

You can check out this 3v4l for a repro case.

Get class name minus namespace without using Reflection

Or simply exploding the return from class_name and getting the last element:

 $class_parts = explode('\\', get_class());
echo end($class_parts);

Or simply removing the namespace from the output of get_class:

echo str_replace(__NAMESPACE__ . '\\', '', get_class());

Either works with or without namespace.

And so on.



Related Topics



Leave a reply



Submit