Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

php - Any more concise way to set default values?

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Is there any better or more concise way than following code to set default value of variables?

$v = isset($v) ? $v : "default value";
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

TL;DR - No, that expression can't be made any shorter.

What you want is for the shortened ternary expression to perform an implicit isset(). This has been discussed on the mailing list and an ifsetor RFC has been created that covers the concept as well.

Since the shortened ternary operator already existed at the time of the above discussion, something like this was proposed using a non-existent operator ??:

// PROPOSAL ONLY, DOES NOT WORK
$v = $v ?? 'default value';

Assign 'default value' if $v is undefined.

However, nothing like this has been implemented in the main language to date. Until then, what you have written can't be made any shorter.

This horrible construct is shorter, but note that it's not the same because it assigns the default value if the variable exists but evaluates to false:

// DO NOT USE
$v = @$v ?: 'default value';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...