因此,为了获得被调用类的类名,我知道两种可能性:@H_403_2@
> get_called_class()
> static :: class@H_403_2@
(get_class($this)表示非静态类)@H_403_2@
为了获得放置代码的类的类名,我知道这三种可能性:@H_403_2@
> get_class()
> __CLASS__
>自我::类@H_403_2@
我现在可能忽视哪些差异?单向另一种方式的潜在冒险和缺点是什么?@H_403_2@
get_class()
@H_403_2@
returns the name of the class of an object@H_403_2@
当您将对象实例指针作为第一个也是唯一的参数传递时,它返回一个类名,包括当前类的限定名称空间(不带参数)或任何指定的对象实例.@H_403_2@
返回限定名称空间和当前类名的魔术常量.在这里,您无法测试其他对象的类名.
根据PHP 5.4,它适用于特征.也就是说,当在类中使用特征时,它将返回该类的名称空间和名称.@H_403_2@
仅自PHP 5.5起可用.它使用类名和命名空间解析来获取信息,因此它不需要事先实例化类.另请注意:@H_403_2@
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.@H_403_2@
测试@H_403_2@
<?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'