问题
We've all encountered it before, needing to print a variable in an input field but not knowing for sure whether the var is set, like this. Basically this is to avoid an e_warning.
<input value='<?php if(isset($var)){print($var);}; ?>'>
How can I write this shorter? I'm okay introducing a new function like this:
<input value='<?php printvar('myvar'); ?>'>
But I don't succeed in writing the printvar() function.
回答1:
For PHP >= 5.x:
My recommendation would be to create a issetor
function:
function issetor(&$var, $default = false) {
return isset($var) ? $var : $default;
}
This takes a variable as argument and returns it, if it exists, or a default value, if it doesn't. Now you can do:
echo issetor($myVar);
But also use it in other cases:
$user = issetor($_GET['user'], 'guest');
For PHP >= 7.0:
As of PHP 7 you can use the null-coalesce operator:
$user = $_GET['user'] ?? 'guest';
Or in your usage:
<?= $myVar ?? '' ?>
回答2:
Another option:
<input value="<?php echo isset($var) ? $var : '' ?>">
回答3:
<input value='<?php @print($var); ?>'>
回答4:
The shortest answer I can come up with is <?php isset($var) AND print($var); ?>
Further details are here on php manual.
'; // This is an alternative isset( $value ) AND print( $value ); ?>A simple alternative to an if statement, which is almost like a ternary operator, is the use of AND. Consider the following:
This does not work with echo() for some reason. I find this extremely useful!
回答5:
Better use a proper template engine - https://stackoverflow.com/q/3694801/298479 mentions two nice ones.
Here's your function anyway - it will only work if the var exists in the global scope:
function printvar($name) {
if(isset($GLOBALS[$name])) echo $GLOBALS[$name];
}
回答6:
You could do <?php echo @$var; ?>.
Or <?= @$var ?>
.
回答7:
There's currently nothing in PHP that can do this, and you can't really write a function in PHP to do it either. You could do the following to achieve your goal, but it also has the side effect of defining the variable if it doesn't exist:
function printvar(&$variable)
{
if (isset($variable)) {
echo $variable;
}
}
This will allow you to do printvar($foo)
or printvar($array['foo']['bar'])
. However, the best way to do it IMO is to use isset
every time. I know it's annoying but there's not any good ways around it. Using @
isn't recommended.
For more information, see https://wiki.php.net/rfc/ifsetor.
回答8:
This worked for me:
<?= isset($my_variable) ? $my_variable : $my_variable="Some Value"; ?>
回答9:
<input value='<?php printvar(&$myvar); ?>' />
function printvar(&$val) {
if (isset($val)) echo $val;
}
回答10:
You could also use the following:
<input type="text" value="<?php echo @$var; ?>">//means if(isset($var)){ echo $var; }
回答11:
$var;
(isset($var)) ? (print $var) : '';
$var = 'hello var';
(isset($var)) ? (print $var) : '';
来源:https://stackoverflow.com/questions/5836515/what-is-the-php-shorthand-for-print-var-if-var-exist