24

I know there is a static class field on PHP 5.5, but I have to stick to PHP 5.4. Is it possible to get the fully qualified class name from a variable?

Example:

namespace My\Awesome\Namespace

class Foo {

}

And somewhere else in the code:

public function bar() {
   $var = new \My\Awesome\Namespace\Foo();

   // maybe there's something like this??
   $fullClassName = get_qualified_classname($var);

   // outputs 'My\Awesome\Namespace\Foo'
   echo $fullClassName 
}
1

3 Answers 3

32

You should be using get_class

If you are using namespaces this function will return the name of the class including the namespace, so watch out if your code does any checks for this.

namespace Shop; 

<?php 
class Foo 
{ 
  public function __construct() 
  { 
     echo "Foo"; 
  } 
} 

//Different file 

include('inc/Shop.class.php'); 

$test = new Shop\Foo(); 
echo get_class($test);//returns Shop\Foo 

This is a direct copy paste example from here

16

I know this is an old question, but for people still finding this, I would suggest this approach:

namespace Foo;

class Bar
{
    public static function fqcn()
    {
        return __CLASS__;
    }
}

// Usage:
use Foo\Bar;
// ...
Bar::fqcn(); // Return a string of Foo\Bar

If using PHP 5.5, you can simply do this:

namespace Foo;

class Bar
{}

// Usage:
use Foo\Bar;
// ...
Bar::class; // Return a string of Foo\Bar

Hope this helps...

More info on ::class here.

0
7

For developers using PHP 8.0 and above, you can now easily do this without get_class.

PHP8 introduced the support for ::class on objects. Example:


public function bar() {
   $var = new \My\Awesome\Namespace\Foo();

   echo $var::class;
}

Here's the RFC for more info.

Not the answer you're looking for? Browse other questions tagged or ask your own question.