PHP的缩写是什么:如果var存在,则打印var [英] What is the PHP shorthand for: print var if var exist
本文介绍了PHP的缩写是什么:如果var存在,则打印var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们以前都遇到过,需要在输入字段中打印一个变量,但不确定是否像这样设置了var.基本上,这是为了避免发出e_warning.
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'); ?>'>
但是我没有成功编写printvar()函数.
But I don't succeed in writing the printvar() function.
推荐答案
对于PHP> = 5.x:
我的建议是创建一个issetor
函数:
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');
对于PHP> = 7.0:
从PHP 7开始,您可以使用空值运算符:
$user = $_GET['user'] ?? 'guest';
或根据您的用法:
<?= $myVar ?? '' ?>
这篇关于PHP的缩写是什么:如果var存在,则打印var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文