简体   繁体   English

没有此类属性时 DOMElement::getAttribute() 返回空字符串的原因

[英]Reason for DOMElement::getAttribute() returning an empty string when there is no such attribute

In the php docs it says:php 文档中它说:

Return Values返回值

The value of the attribute, or an empty string if no attribute with the given name is found.属性的值,如果没有找到具有给定名称的属性,则为空字符串。

Does anybody know the reason for returning an empty string instead of just NULL ?有谁知道返回空字符串而不仅仅是NULL的原因?

The point is that the DOM specification is not platform-specific.关键是 DOM 规范不是特定于平台的。 It was written to be implemented in a wide variety of programming languages, so it tends not to assume the existence of types such as null .它被编写为用多种编程语言实现,因此它倾向于不假设存在诸如null之类的类型。 The W3C can assume the existence of a string type, so it's safe to use an empty string. W3C 可以假定存在字符串类型,因此使用空字符串是安全的。

So the specification reads as this:所以规范是这样写的:

DOMString                 getAttribute(in DOMString name);

So a string is the expected type on a cross-platform basis.因此,字符串是跨平台的预期类型。 PHP's DOMDocument conforms to this. PHP 的 DOMDocument 符合这一点。

I don't think it really matters what it returns.我认为它返回什么并不重要。 To check the validity of the result you need to call DOMElement::hasAttribute() anyway.要检查结果的有效性,您无论如何都需要调用DOMElement::hasAttribute()

It could be just because they want to keep it simple and have everything return strings instead of a magic value of a different type (like null ).这可能只是因为他们希望保持简单并让所有内容都返回字符串而不是不同类型的魔法值(如null )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM