Yii2 中::class 与::className() 的区别?

2022-01-04 00:00:00 php yii2 yii

我知道两者都给出了相同的结果,但我很期待听到有关性能的消息.

i know both gives same results but i am looking forward to hear about performance.

我不确定,但我认为..

i am not sure but i think..

  • "MyClass::className()" 导致类文件也被加载(它的 Yii 函数的主体只是 get_Called_class())

  • "MyClass::className()" cause that class file to be loaded as well (its Yii function whom body is just simply get_called_class())

"MyClass::class" 我认为这个 php 的原生类属性不会加载类 php 文件,只是根据当前命名空间或 use.

"MyClass::class" i think this php's native class property don't load class php file and just return its name based on current namespace or use.

让我知道我是否正确?或请突出您的知识.

Let me know if i am right? or highlight your knowledge please.

有很多地方我们只想要完整的限定类名称,即使当时不会使用它.但我也不喜欢放置硬编码字符串(由于硬重构)

There are many places where we just want full qualitfied class name even it's not going to be used that time. but i also don't like putting hardcoded strings (due to hard refactoring)

推荐答案

是的,我刚刚发现我是对的.

Yes i just found i was right.

PHP 的原生类属性可以节省性能..(PHP 5.5+)

PHP's native class property is performance saving..(PHP 5.5+)

见这里http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.class.class.name

所以这不会导致加载类文件,所以即使类不存在它也会返回完整的类名

so this don't cause class file to be loaded, so even if class doesn't exists it will return full className

注意:使用::class的类名解析是编译时转型.这意味着当时类名字符串是created 尚未发生自动加载.因此,类名即使该类不存在,也会被扩展.没有错误发出那种情况.

Note: 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.

相关文章