PHP 5.4:获取实例变量的全限定类名 [英] PHP 5.4: Getting Fully-qualified class name of an instance variable

查看:294
本文介绍了PHP 5.4:获取实例变量的全限定类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道PHP 5.5上有一个静态class字段,但是我必须坚持使用PHP 5.4.是否可以从变量获取完全限定的类名?

示例:

namespace My\Awesome\Namespace

class Foo {

}

以及代码中的其他地方:

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 
}

解决方案

您应该使用 get_class

如果您使用的是名称空间,则此函数将返回包含名称空间的类的名称,因此请注意您的代码是否对此进行任何检查.

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 

这是来自 here 的直接复制粘贴示例>

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 
}

解决方案

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

这篇关于PHP 5.4:获取实例变量的全限定类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆