如何在 PHP 中获取类名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15103810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:34:53  来源:igfitidea点击:

How do I get class name in PHP?

php

提问by Rezan Achmad

public class MyClass {

}

In Java, we can get class name with String className = MyClass.class.getSimpleName();

在 Java 中,我们可以使用 String className = MyClass.class.getSimpleName();

How to do this in PHP? I already know get_class(), but it works only for objects. Currently I work in Active Record. I need statement like MyClass::className.

如何在 PHP 中做到这一点?我已经知道了get_class(),但它只适用于对象。目前我在 Active Record 工作。我需要像MyClass::className.

回答by Dado

Since PHP 5.5you can use class name resolution via ClassName::class.

从 PHP 5.5 开始,您可以通过ClassName::class使用类名解析。

See new features of PHP5.5.

查看PHP5.5 的新特性

<?php

namespace Name\Space;

class ClassName {}

echo ClassName::class;

?>

If you want to use this feature in your class method use static::class:

如果要在类方法中使用此功能,请使用static::class

<?php

namespace Name\Space;

class ClassName {
   /**
    * @return string
    */
   public function getNameOfClass()
   {
      return static::class;
   }
}

$obj = new ClassName();
echo $obj->getNameOfClass();

?>

For older versions of PHP, you can use get_class().

对于旧版本的 PHP,您可以使用get_class()

回答by Brad

You can use __CLASS__within a class to get the name.

您可以__CLASS__在类中使用来获取名称。

http://php.net/manual/en/language.constants.predefined.php

http://php.net/manual/en/language.constants.predefined.php

回答by None

It sounds like you answered your own question. get_classwill get you the class name. It is procedural and maybe that is what is causing the confusion. Take a look at the php documentation for get_class

听起来你回答了你自己的问题。get_class将为您提供班级名称。这是程序性的,也许这就是造成混乱的原因。看一看php文档get_class

Here is their example:

这是他们的例子:

 <?php

 class foo 
 {
     function name()
     {
         echo "My name is " , get_class($this) , "\n";
     }
 }

 // create an object
 $bar = new foo();

 // external call
 echo "Its name is " , get_class($bar) , "\n"; // It's name is foo

 // internal call
 $bar->name(); // My name is foo

To make it more like your example you could do something like:

为了使它更像您的示例,您可以执行以下操作:

 <?php

 class MyClass
 {
       public static function getClass()
       {
            return get_class();
       }
 }

Now you can do:

现在你可以这样做:

 $className = MyClass::getClass();

This is somewhat limited, however, because if my class is extended it will still return 'MyClass'. We can use get_called_classinstead, which relies on Late Static Binding, a relatively new feature, and requires PHP >= 5.3.

然而,这在某种程度上是有限的,因为如果我的课程被扩展,它仍然会返回“MyClass”。我们可以get_called_class改用它,它依赖于Late Static Binding,这是一个相对较新的特性,并且需要 PHP >= 5.3。

<?php

class MyClass
{
    public static function getClass()
    {
        return get_called_class();
    }

    public static function getDefiningClass()
    {
        return get_class();
    }
}

class MyExtendedClass extends MyClass {}

$className = MyClass::getClass(); // 'MyClass'
$className = MyExtendedClass::getClass(); // 'MyExtendedClass'
$className = MyExtendedClass::getDefiningClass(); // 'MyClass'

回答by Rezan Achmad

Now, I have answer for my problem. Thanks to Bradfor the link, I find the answer here. And thanks to J.Moneyfor the idea. My solution:

现在,我有我的问题的答案。感谢Brad提供的链接,我在这里找到了答案。并感谢J.Money的想法。我的解决方案:

<?php

class Model
{
    public static function getClassName() {
        return get_called_class();
    }
}

class Product extends Model {}

class User extends Model {}

echo Product::getClassName(); // "Product" 
echo User::getClassName(); // "User" 

回答by Omar Makled

To get class name you can use ReflectionClass

要获取类名,您可以使用 ReflectionClass

class MyClass {
    public function myNameIs(){
        return (new \ReflectionClass($this))->getShortName();
    }
}

回答by JerzySkalski

I think it's important to mention little difference between 'self' and 'static' in PHP as 'best answer' uses 'static' which can give confusing result to some people.

我认为重要的是要提及 PHP 中“自我”和“静态”之间的细微差别,因为“最佳答案”使用了“静态”,这可能会给某些人带来令人困惑的结果。

<?php
class X {
    function getStatic() {
        // gets THIS class of instance of object
        // that extends class in which is definied function
        return static::class;
    }
    function getSelf() {
        // gets THIS class of class in which function is declared
        return self::class;
    }
}

class Y extends X {
}
class Z extends Y {
}

$x = new X();
$y = new Y();
$z = new Z();

echo 'X:' . $x->getStatic() . ', ' . $x->getSelf() . 
    ', Y: ' . $y->getStatic() . ', ' . $y->getSelf() . 
    ', Z: ' . $z->getStatic() . ', ' . $z->getSelf();

Results:

结果:

X: X, X
Y: Y, X
Z: Z, X

回答by Илья Зеленько

It looks like ReflectionClassis a pretty productive option.

看起来ReflectionClass是一个非常有成效的选择。

class MyClass {
    public function test() {
        // 'MyClass'
        return (new \ReflectionClass($this))->getShortName();
    }
}

Benchmark:

基准:

Method Name      Iterations    Average Time      Ops/second
--------------  ------------  --------------    -------------
testExplode   : [10,000    ] [0.0000020221710] [494,518.01547]
testSubstring : [10,000    ] [0.0000017177343] [582,162.19968]
testReflection: [10,000    ] [0.0000015984058] [625,623.34059]

回答by CallMarl

end(preg_split("#(\\\\|\\/)#", Class_Name::class))

end(preg_split("#(\\\\|\\/)#", Class_Name::class))

Class_Name::class: return the class with the namespace. So after you only need to create an array, then get the last value of the array.

Class_Name::class: 返回具有命名空间的类。所以在你只需要创建一个数组之后,然后获取数组的最后一个值。

回答by 23Pstars

<?php
namespace CMS;
class Model {
  const _class = __CLASS__;
}

echo Model::_class; // will return 'CMS\Model'

for older than PHP 5.5

早于PHP 5.5

回答by Lukas Correa

echo substr(strrchr(__CLASS__, "\"), 1);