PHP 5.4: Getting Fully-qualified class name of an

2019-04-19 01:43发布

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 
}

2条回答
Summer. ? 凉城
2楼-- · 2019-04-19 01:55

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

查看更多
混吃等死
3楼-- · 2019-04-19 02:21

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.

查看更多
登录 后发表回答