'??'的功能:簡(jiǎn)化您的PHP應(yīng)用程序中的無效檢查
Jul 30, 2025 am 05:04 AM??操作符是PHP 7引入的空合并操作符,用于簡(jiǎn)潔地處理null值檢查。 1. 它首先檢查變量或數(shù)組鍵是否存在且不為null,若是則返回該值,否則返回默認(rèn)值,如$array['key'] ?? 'default'。 2. 相比isset()與三元運(yùn)算符結(jié)合的方式,??更簡(jiǎn)潔且支持鏈?zhǔn)秸{(diào)用,如$_SESSION'user'['theme'] ?? $_COOKIE['theme'] ?? 'light'。 3. 常用于安全處理表單輸入、配置讀取和對(duì)象屬性訪問,但僅判斷null,不識(shí)別''、0或false為“空”。 4. 使用時(shí)需注意避免訪問不存在的嵌套結(jié)構(gòu)導(dǎo)致警告,可通過輔助函數(shù)如array_get實(shí)現(xiàn)安全遍歷。 5. 盡管功能有限,??在提升代碼可讀性和安全性方面效果顯著,是現(xiàn)代PHP開發(fā)中的推薦實(shí)踐。
Null checks are a common part of any PHP application. Whether you're pulling data from a database, processing user input, or reading configuration values, you've probably written more than a few isset()
or !empty()
checks in your time. But there's a cleaner, more concise way to handle these scenarios — and it starts with two simple question marks: ??
.

What Is the Null Coalescing Operator ( ??
)?
The ??
operator, known as the null coalescing operator , was introduced in PHP 7. It provides a neat way to check whether a variable or array key exists and is not null — and if it isn't, fall back to a default value.
Here's how it works:

$value = $array['key'] ?? 'default';
This line means:
"If $array['key']
exists and is not null, assign it to $value
. Otherwise, use 'default'
."
It's functionally similar to:

$value = isset($array['key']) ? $array['key'] : 'default';
But much cleaner and easier to read — especially when chaining multiple checks.
Why ??
Beats Ternary isset()
Before PHP 7, handling undefined array keys safely meant wrapping ternary expressions in isset()
:
$username = isset($_GET['user']) ? $_GET['user'] : 'guest';
Not only is this verbose, but nesting these checks quickly becomes messy:
$theme = isset($_SESSION['user']['preferences']['theme']) ? $_SESSION['user']['preferences']['theme'] : 'light';
With ??
, you can simplify deeply nested fallbacks:
$theme = $_SESSION['user']['preferences']['theme'] ?? 'light';
And even chain multiple fallbacks:
$theme = $_SESSION['user']['preferences']['theme'] ?? $_COOKIE['theme'] ?? 'light';
Each operand is evaluated left to right, returning the first one that exists and is not null.
Common Use Cases for ??
in Real Applications
Using ??
effectively can make your code more robust and readable. Here are some practical examples:
Handling form inputs safely:
$email = $_POST['email'] ?? null;
Fetching configuration with fallbacks:
$apiUrl = config('services.api.url') ?? 'https://api.example.com';
Working with optional object properties:
$title = $post->title ?? 'No title provided';
?? Note:
??
only checks fornull
. It will return values like''
,0
, orfalse
. If you need to treat those as "empty" too, stick withempty()
or combine checks as needed.
Avoiding Common Pitfalls
While ??
is powerful, it's important to understand what it doesn't do:
- It doesn't check if a value is logically empty — just if it's set and not null.
- It won't prevent warnings if you access an invalid array structure without proper nesting checks.
For example:
// This may still cause a warning if $_SESSION['user'] doesn't exist $theme = $_SESSION['user']['preferences']['theme'] ?? 'light';
To avoid this, ensure the full path exists or use nested ??
carefully. One workaround is to use functions or helpers that safely traverse arrays:
function array_get($array, $path, $default = null) { foreach (explode('.', $path) as $key) { if (!is_array($array) || !isset($array[$key])) { return $default; } $array = $array[$key]; } return $array; } $theme = array_get($_SESSION, 'user.preferences.theme', 'light');
But for simple cases, ??
still wins in clarity and speed.
Basically, ??
is a small syntax feature that brings big improvements in code readability and safety when dealing with potentially null values. Once you start using it, you'll wonder how you lived without it.
以上是'??'的功能:簡(jiǎn)化您的PHP應(yīng)用程序中的無效檢查的詳細(xì)內(nèi)容。更多信息請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣服圖片

Undresser.AI Undress
人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover
用于從照片中去除衣服的在線人工智能工具。

Clothoff.io
AI脫衣機(jī)

Video Face Swap
使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費(fèi)的代碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6
視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版
神級(jí)代碼編輯軟件(SublimeText3)

Replaceif/elseassignmentswithternariesorlogicaloperatorslike||,??,and&&forconcise,clearintent.2.Useobjectmappinginsteadofif/elseifchainstocleanlyresolvemultiplevaluechecks.3.Applyearlyreturnsviaguardclausestoreducenestingandhighlightthemainfl

OperatorPrecedEdendEdedEterminEseValuationOrderInshorthandConcortionals,其中&& and || bindmoretightlythan?:s soexpressionslik ea || b?c:dareinterpretedas(a || b)?c:d,nota ||(b?c:d); 1.AlwaysUseparentSeparentHiseStoclarifyIntent,Susteasa ||(b?c:d)或(a && b)?x :( c

??操作符是PHP7引入的空合并操作符,用于簡(jiǎn)潔地處理null值檢查。1.它首先檢查變量或數(shù)組鍵是否存在且不為null,若是則返回該值,否則返回默認(rèn)值,如$array['key']??'default'。2.相比isset()與三元運(yùn)算符結(jié)合的方式,??更簡(jiǎn)潔且支持鏈?zhǔn)秸{(diào)用,如$_SESSION'user'['theme']??$_COOKIE['theme']??'light'。3.常用于安全處理表單輸入、配置讀取和對(duì)象屬性訪問,但僅判斷null,不識(shí)別''、0或false為“空”。4.使用時(shí)

Elvis操作符(?:)用于返回左側(cè)真值或右側(cè)默認(rèn)值,1.當(dāng)左側(cè)值為真(非null、false、0、''等)時(shí)返回左側(cè)值;2.否則返回右側(cè)默認(rèn)值;適用于變量賦默認(rèn)值、簡(jiǎn)化三元表達(dá)式、處理可選配置;3.但需避免在0、false、空字符串為有效值時(shí)使用,此時(shí)應(yīng)改用空合并操作符(??);4.與??不同,?:基于真值判斷,??僅檢查null;5.常見于Laravel響應(yīng)輸出和Blade模板中,如$name?:'Guest';正確理解其行為可安全高效地用于現(xiàn)代PHP開發(fā)。

returnEarlyToreDucenestingByExitingFunctionsAssoonAsoonAsoonValidoredGecasesaredeTected,由此產(chǎn)生的InflatterandMoreAdableCode.2.useGuardClausesattheBebeginningBeginningNingningOffunctionStohandlePreconditionSangeptionSankeptionSankequemainLogogicunClutter.3.ReplaceceConditionAlboolBoolBooleAnterNerternswi

使用三元運(yùn)算符時(shí)應(yīng)優(yōu)先考慮代碼清晰性而非單純縮短代碼;2.避免嵌套三元運(yùn)算符,因其會(huì)增加理解難度,應(yīng)改用if-elseif-else結(jié)構(gòu);3.可結(jié)合空合并運(yùn)算符(??)處理null情況,提升代碼安全性與可讀性;4.在返回簡(jiǎn)單條件值時(shí)三元運(yùn)算符更有效,但若直接返回布爾表達(dá)式則無需冗余使用;最終原則是三元運(yùn)算符應(yīng)降低認(rèn)知負(fù)擔(dān),僅在使代碼更清晰時(shí)使用,否則應(yīng)選擇if-else結(jié)構(gòu)。

NestedternaryoperatorsinPHPshouldbeavoidedbecausetheyreducereadability,asseenwhencomparingaconfusingnestedternarytoitsproperlyparenthesizedbutstillhard-to-readform;2.Theymakedebuggingdifficultsinceinlinedebuggingismessyandsteppingthroughconditionsisn

PHP的三元運(yùn)算符是一種簡(jiǎn)潔的if-else替代方式,適用于簡(jiǎn)單條件賦值,能提升代碼可讀性;1.使用三元運(yùn)算符時(shí)應(yīng)確保邏輯清晰,僅用于簡(jiǎn)單判斷;2.避免嵌套三元運(yùn)算符,因其會(huì)降低可讀性,應(yīng)改用if-elseif-else結(jié)構(gòu);3.優(yōu)先使用null合并運(yùn)算符(??)處理null或未定義值,用elvis運(yùn)算符(?:)判斷真值性;4.保持表達(dá)式簡(jiǎn)短,避免副作用,始終以可讀性為首要目標(biāo);正確使用三元運(yùn)算符可使代碼更簡(jiǎn)潔,但不應(yīng)為了減少行數(shù)而犧牲清晰性,最終原則是保持簡(jiǎn)單、可測(cè)試且不嵌套。
