<>和有什么区别?和!= [英] What is the difference between <> and !=
问题描述
在PHP中检查不相等(不检查类型),您可以执行以下操作:
if( A != B ) {
DO SOMETHING;
}
但是您也可以执行此操作,其结果相同:
if( A <> B ) {
DO SOMETHING;
}
有什么区别吗?
在<>
上使用!=
会以任何方式,形状或形式更改评估吗?
忘记文档一分钟,让我们检查一下源代码.让我们从扫描仪(lexer):
开始<ST_IN_SCRIPTING>"!="|"<>" {
return T_IS_NOT_EQUAL;
}
因此它们解析为相同的令牌.让我们看看解析器:
expr T_IS_NOT_EQUAL expr { zend_do_binary_op(ZEND_IS_NOT_EQUAL, &$$, &$1, &$3 TSRMLS_CC); }
所以我们知道触发的操作码是ZEND_IS_NOT_EQUAL
...
现在,让我们看看操作:>
static int ZEND_FASTCALL ZEND_IS_NOT_EQUAL_SPEC_CONST_CONST_HANDLER(ZEND_OPCODE_HANDLER_ARGS)
{
USE_OPLINE
zval *result = &EX_T(opline->result.var).tmp_var;
SAVE_OPLINE();
ZVAL_BOOL(result, fast_not_equal_function(result,
opline->op1.zv,
opline->op2.zv TSRMLS_CC));
CHECK_EXCEPTION();
ZEND_VM_NEXT_OPCODE();
}
所以实际上没有什么区别.由于它们解析为相同的令牌,因此它们具有完全相同的优先级(因此文档是错误的或具有误导性的).由于他们使用相同的执行程序,并且操作码例程中没有决策点,因此它们执行相同的代码.
是的,<>
和!=
是100%可互换的,并且绝对没有技术上的理由来使用一个.
话虽如此,保持一致可以带来很多重要的收获.因此,我建议您坚持使用!=
并完成操作...
编辑
我已经更新了文档以反映这一点,并解决了另一个优先顺序问题(++和-与强制转换的优先顺序相同).在 docs.php.net
上进行检查In PHP to check non-equality (without checking type) you can do this:
if( A != B ) {
DO SOMETHING;
}
But you can also do this, which has the same result:
if( A <> B ) {
DO SOMETHING;
}
Is there any difference?
Does using !=
over <>
change the evaluation in any way, shape, or form?
Forgetting documentation for a minute, let's check out the source code. Let's start with the scanner (lexer):
<ST_IN_SCRIPTING>"!="|"<>" {
return T_IS_NOT_EQUAL;
}
So they parse to the same token. Let's check out the parser:
expr T_IS_NOT_EQUAL expr { zend_do_binary_op(ZEND_IS_NOT_EQUAL, &$$, &$1, &$3 TSRMLS_CC); }
So we know that the opcode that's fired is ZEND_IS_NOT_EQUAL
...
Now, let's check out the operation:
static int ZEND_FASTCALL ZEND_IS_NOT_EQUAL_SPEC_CONST_CONST_HANDLER(ZEND_OPCODE_HANDLER_ARGS)
{
USE_OPLINE
zval *result = &EX_T(opline->result.var).tmp_var;
SAVE_OPLINE();
ZVAL_BOOL(result, fast_not_equal_function(result,
opline->op1.zv,
opline->op2.zv TSRMLS_CC));
CHECK_EXCEPTION();
ZEND_VM_NEXT_OPCODE();
}
So there's literally no difference. Since they parse to the same token, they have exactly the same precedence (so the docs are either wrong or misleading). Since they use the same executor, and there's no decision point in the opcode routine, they execute identical code.
So yes, <>
and !=
are 100% interchangeable, and there's absolutely no technical reason to use one over the other.
With that said, there is something significant to gain by being consistent. So I'd recommend just sticking with !=
and being done with it...
Edit
I've updated the docs to reflect this, and fixed another issue with the precedence order (++ and -- have the same precedence as casting). Check it out on docs.php.net
这篇关于<>和有什么区别?和!=的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!