gpt4 book ai didi

php - 区别 static::class vs get_called_class() 和 __CLASS__ vs get_class() vs self::class

转载 作者:可可西里 更新时间:2023-11-01 12:35:20 25 4
gpt4 key购买 nike

我见过几个线程,人们在其中询问如何在 PHP 中获取类或对象的名称。但是,我在任何地方都看不到所解释的各种可能性之间的区别。我希望这里有人可以帮助我。

所以为了得到被调用类的类名,我知道两种可能:

  1. get_called_class()

  2. static::class

(非静态类的get_class($this))

为了获取放置代码的类的类名,我知道这三种可能性:

  1. get_class()

  2. __CLASS__

  3. self::class

是否有任何我现在可以忽略的差异?一种方式相对于另一种方式的潜在优势和劣势是什么?

最佳答案

之间的差异

get_class()

returns the name of the class of an object

当您将对象实例指针作为第一个也是唯一的参数传递时,它返回一个类名,包括其当前类(无参数)或任何指定对象实例的限定命名空间。

__CLASS__

返回限定命名空间和当前类名的神奇常量。在这里您不能测试其他对象的类名。根据 PHP 5.4,它适用于特征。也就是说,当在类中使用特征时,它将返回该类的命名空间和名称。

::class

仅在 PHP 5.5 之后可用。它使用类名和命名空间解析来获取信息,因此不需要事先实例化类。另请注意:

The class name resolution using ::class is a compile time transformation. That means at the time the class name string is created no autoloading has happened yet. As a consequence, class names are expanded even if the class does not exist. No error is issued in that case.

测试

<?php
namespace nTest;
trait tTest {
function __toString() {return get_class();}
function className() {return __CLASS__;} // per PHP 5.4
function traitName() {return __TRAIT__;}
}
class cTest {
use tTest;
function usedTraitName() {return __TRAIT__;}
}
class cClassWithoutObject {}
$oTest = new cTest;

header('Content-type: text/plain');
print // Output:
$oTest . PHP_EOL // 'nTest::cTest'
. get_class($oTest) . PHP_EOL // 'nTest::cTest'
. $oTest->className() . PHP_EOL // 'nTest::cTest'
. $oTest->traitName() . PHP_EOL // 'nTest::tTest' (trait!)
. $oTest->usedTraitName() . PHP_EOL // '' (no trait!)
. cTest::class . PHP_EOL // 'nTest::cTest'
. cClassWithoutObject::class; // 'nTest::cTestNotInstantiated'

关于php - 区别 static::class vs get_called_class() 和 __CLASS__ vs get_class() vs self::class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47798831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com