Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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  } 
like image 533
leypascua Avatar asked Apr 03 '14 10:04

leypascua


People also ask

What is fully qualified class name in PHP?

Fully qualified name. This is an identifier with a namespace separator that begins with a namespace separator, such as \Foo\Bar . The namespace \Foo is also a fully qualified name. Relative name. This is an identifier starting with namespace , such as namespace\Foo\Bar .

How to make an instance of a class in PHP?

To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).

What does :: class do in PHP?

SomeClass::class will return the fully qualified name of SomeClass including the namespace. This feature was implemented in PHP 5.5. It's very useful for 2 reasons. You can use the use keyword to resolve your class and you don't need to write the full class name.

How do I find the instance of an object in PHP?

PHP | get_class() Function Return Value: This function returns the class name of which object is an instance. It returns FALSE if the object is not an object. If the object is omitted when inside the class then the class name is returned. $obj = new GFG();


1 Answers

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

like image 199
Shankar Narayana Damodaran Avatar answered Oct 03 '22 04:10

Shankar Narayana Damodaran