之间的差异
returns the name of the class of an object
当您将对象实例指针作为第一个也是唯一的参数传递时,它返回一个类名,包括当前类的限定名称空间(不带参数)或任何指定的对象实例.
返回限定名称空间和当前类名的魔术常量.在这里,您无法测试其他对象的类名.
根据PHP 5.4,它适用于特征.也就是说,当在类中使用特征时,它将返回该类的名称空间和名称.
仅自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.
测试
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'