在PHP中首先使用null有什么好处?

编程入门 行业动态 更新时间:2024-10-13 22:26:43
本文介绍了在PHP中首先使用null有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: 为什么一些有经验的程序员用变量前的值写比较?

Possible Duplicate: Why do some experienced programmers write comparisons with the value before the variable?

我对此感到很好奇:在我研究过的大多数框架/开源项目中,我经常看到这样的代码...

I am just curious about this: in most frameworks/opensource projects I have studied, I often seen code like this...

<?php if (null === self::$_instance) { self::$_instance = new self(); }

特别是这一行...

if (null === self::$_instance) {

为什么在if语句的第一个参数中使用null而不是相反?...

Why use null in the first argument of the if statement instead of the other way around?...

if (self::$_instance === null) {

我意识到可能没有性能提升或类似的提升.这只是偏好还是我忽略的某种编码标准?

I realize there is probably no performance increase or anything like that. Is this just a preference or is it some kind of coding standard I have overlooked?

推荐答案

它可以防止您意外地将值分配给变量,尤其是在仅使用松散类型比较(==)时:

It prevents you from accidentally assigning the value to a variable, especially when only using loose type comparison (==):

if (self::$_instance = NULL) { … } // WHOOPS!, self::$_instance is now NULL

这种条件类型通常称为 yoda条件.在性能方面没有区别,两条语句是等效的.

This style of conditions is often called yoda conditions. Performance wise there is no difference, both statements are equivalent.

更多推荐

在PHP中首先使用null有什么好处?

本文发布于:2023-11-29 12:18:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646374.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么好处   PHP   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!