Does PHP have a default assignment idiom like perl?
In Perl, if I want to default a value that might exist, for example as a开发者_如何学运维 passed in parameter, I can do this:
$var = parm->('variable') || 'default';
Is there something analogous in PHP or do I have to check the value after assigning, and if it is still null assign it the default value?
Not exactly.
PHP 5.3 introduced what they call "the ternary shortcut".
// old way
$foo = $foo ? $foo : 'default';
// new way in 5.3
$foo = $foo ?: 'default';
Which isn't even that much of a shortcut and only works short-circuit-able values (if 0
is a valid value for $foo
this shortcut will fail.)
Otherwise you'll have to do the type/existence checking the old, hard, manual way.
You can also specify default values for parameters in the signature - not sure if that's exactly what you're getting at but here's that in action
function foo( $bar = 'baz' )
{
echo $bar;
}
foo(); // baz
$var = (!empty($foo)) ? $foo : 'default';
I think the standard ternary is defacto in PHP:
$var = $foo ? $foo : 'default';
echo $foo ? $foo : 'default';
But there are a couple other tricks that can be a little cleaner in some cases:
//these are very close but can't be echo'd inline like a ternary
$var = $foo OR $var = 'default';//assigning a default to $var if $foo is falsy
($var = $foo) || $var = 'default';//same effect as above
isset($var) || $var = 'default';//making sure $var is set
Here's one that can be echo'd inline:
$var = ($foo) ?: 'default';//partial ternary
echo ($foo) ?: 'default';//aka ternary shortcut (PHP 5.3+ only)
An important note is that a lot of these can emit errors when vars are not set :(
echo @($foo) ?: 'default';//@ fixes it but isn't considered good practice
One place it may be worth not using the ternary approach is when they're nested:
$user = (($user)?$user:(($user_name)?$user_name:(($user_id)?$user_id:'User')));
echo 'Welcome '.$user;//is pretty messy
($user = $user) || ($user = $user_name) || ($user = $user_id) || ($user = 'User');
echo 'Welcome '.$user;//is more readable
Anyway, lot's of fun to explore.
精彩评论