Skip to content
Advertisement

PHP 5.4: Getting Fully-qualified class name of an instance variable

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 MyAwesomeNamespace

class Foo {

}

And somewhere else in the code:

public function bar() {
   $var = new MyAwesomeNamespaceFoo();

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

   // outputs 'MyAwesomeNamespaceFoo'
   echo $fullClassName 
}

Advertisement

Answer

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 ShopFoo(); 
echo get_class($test);//returns ShopFoo 

This is a direct copy paste example from here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement