Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

php - Setting default values (conditional assignment)

In Ruby you can easily set a default value for a variable

x ||= "default"

The above statement will set the value of x to "default" if x is nil or false

Is there a similar shortcut in PHP or do I have to use the longer form:

$x = (isset($x))? $x : "default";

Are there any easier ways to handle this in PHP?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

As of PHP 5.3 you can use the ternary operator while omitting the middle argument:

$x = $x ?: 'default';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...