PHP 的简写是什么:如果 var 存在则打印 var
我们以前都遇到过这种情况,需要在输入字段中打印变量,但不确定变量是否已设置,就像这样。基本上这是为了避免 e_warning。
<input value='<?php if(isset($var)){print($var);}; ?>'>
我怎样才能写得更短呢?我可以引入这样的新函数:
<input value='<?php printvar('myvar'); ?>'>
但是我没有成功编写 printvar() 函数。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
另一种选择:
Another option:
我能想到的最短答案是
更多详细信息请参见 php 手册< /a>.
';
// This is an alternative
isset( $value ) AND print( $value );
?>
由于某种原因,这不适用于 echo()。我发现这非常有用!
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 );
?>
This does not work with echo() for some reason. I find this extremely useful!
最好使用合适的模板引擎 - https://stackoverflow.com/q/3694801/298479 提到了两个不错的模板引擎。
无论如何,这就是你的函数 - 只有当 var 存在于全局范围内时它才会起作用:
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:
你可以做
.
或。
You could do
<?php echo @$var; ?>.
Or<?= @$var ?>
.目前 PHP 中没有任何东西可以做到这一点,而且您也无法真正在 PHP 中编写函数来做到这一点。您可以执行以下操作来实现您的目标,但如果变量不存在,它也会产生定义变量的副作用:
这将允许您执行
printvar($foo)
或printvar($array['foo']['bar'])
.然而,在我看来,最好的方法是每次都使用isset
。我知道这很烦人,但没有任何好的方法可以解决。不建议使用@
。有关详细信息,请参阅 https://wiki.php.net/rfc/ifsetor。
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:
This will allow you to do
printvar($foo)
orprintvar($array['foo']['bar'])
. However, the best way to do it IMO is to useisset
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.
这对我有用:
This worked for me:
您还可以使用以下内容:
You could also use the following:
对于 PHP >= 7.0:
从 PHP 7 开始,您可以使用 空合并运算符:
或者在您的用法中:
对于 PHP >= 5.x:
我的建议是创建一个
issetor
函数:这需要一个变量作为参数,如果存在则返回它,如果不存在则返回默认值。现在你可以这样做:
但也可以在其他情况下使用它:
For PHP >= 7.0:
As of PHP 7 you can use the null-coalesce operator:
Or in your usage:
For PHP >= 5.x:
My recommendation would be to create a
issetor
function:This takes a variable as argument and returns it, if it exists, or a default value, if it doesn't. Now you can do:
But also use it in other cases: