如何在PHP中获取类名?

Rez*_*mad 88 php

public class MyClass {

}
Run Code Online (Sandbox Code Playgroud)

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

如何在PHP中执行此操作?我已经知道get_class(),但它只适用于对象.目前我在Active Record工作.我需要声明MyClass::className.

Dad*_*ado 102

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

查看PHP5.5的新功能.

<?php

namespace Name\Space;

class ClassName {}

echo ClassName::class;

?>
Run Code Online (Sandbox Code Playgroud)

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

<?php

namespace Name\Space;

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

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

?>
Run Code Online (Sandbox Code Playgroud)

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

  • `static :: class`和`get_class_name()`有什么区别? (5认同)
  • @AlexanderJank 似乎在编译时解析了 `static::class`,而在运行时解释了 `get_class_name()`。我通过尝试访问动态生成的类的 ::class 属性(?)并收到以下错误发现了这一点:`Dynamic class names are not allowed in compile-time ::class fetch`。有关更多详细信息,请参阅此 [答案](/sf/answers/2388443221/)。我还发现文档中的 [this note](https://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.class.class) 很有帮助。 (2认同)

Bra*_*rad 26

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

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

  • 你也可以看看这里有趣的所有const:http://php.net/manual/en/language.constants.predefined.php (2认同)
  • @ user1073122,这是我在回答中链接的链接. (2认同)

J.M*_*ney 21

听起来你回答了自己的问题.get_class会得到你的班级名称.这是程序性的,也许是造成混乱的原因.看一下php文档get_class

这是他们的例子:

 <?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
Run Code Online (Sandbox Code Playgroud)

为了使它更像你的例子,你可以做类似的事情:

 <?php

 class MyClass
 {
       public static function getClass()
       {
            return get_class();
       }
 }
Run Code Online (Sandbox Code Playgroud)

现在你可以这样做:

 $className = MyClass::getClass();
Run Code Online (Sandbox Code Playgroud)

但是,这有点受限,因为如果我的类被扩展,它仍然会返回'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'
Run Code Online (Sandbox Code Playgroud)


Rez*_*mad 10

现在,我已经回答了我的问题.感谢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" 
Run Code Online (Sandbox Code Playgroud)

  • 是的我知道..我想避免拼写错误,并且在重新分解类名时(使用IDE工具),我不需要搜索和替换字符串. (7认同)
  • 这没有道理.`FooBar :: getClassName()`总是``FooBar'.如果你可以输入`Product :: getClassName()` - 那么你也可以输入''Product'. (3认同)

Иль*_*ько 8

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

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

基准:

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]

Run Code Online (Sandbox Code Playgroud)


Oma*_*led 7

要获取类名,可以使用ReflectionClass

class MyClass {
    public function myNameIs(){
        return (new \ReflectionClass($this))->getShortName();
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

即使使用命名空间,这也会返回纯类名:

echo substr(strrchr(__CLASS__, "\\"), 1);    
Run Code Online (Sandbox Code Playgroud)


Jer*_*ski 5

我认为重要的是要提到 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();
Run Code Online (Sandbox Code Playgroud)

结果:

X: X, X
Y: Y, X
Z: Z, X
Run Code Online (Sandbox Code Playgroud)