[英]Can 'if X, then echo X' be shortened in PHP?
The shortest way to echo out stuff in views in PHP - when not using template engines - is, afaik, this one: 在PHP中的视图中回显东西的最短路径 - 当不使用模板引擎时 - 是这样的:
<?php if (!empty($x)) echo $x; ?>
For a deeper explanaition why using !empty
is a good choice please look here . 为了更深入的解释,为什么使用
!empty
是一个不错的选择,请看这里 。
Is it possible to write this without writing the variable name twice (like in other languages), something like 是否可以在不编写变量名两次的情况下编写它(就像在其他语言中一样)
!echo $x;
or 要么
echo? $x;
echo @$x;
It's not exactly the right way to do it, but it is shorter. 这不是正确的做法,但它更短。 it reduces the need to check if $x exists since @ silences the error thrown when $x == null;
它减少了检查$ x是否存在的需要,因为@沉默当$ x == null时抛出的错误;
edit 编辑
echo empty($x) ? "" : $x;
is a shorter way, which is not really that much shorter nor does it solve your problem. 是一种较短的方式,它不是那么短,也不能解决你的问题。
guess the other answers offer a better solution by addressing to make a short function for it. 猜测其他答案提供了一个更好的解决方案,通过寻址为它做一个简短的功能。
Built in? 内置? No.
没有。
However - you could write your own wrapper function to do it: 但是 - 您可以编写自己的包装函数来执行此操作:
$x = 'foobar';
myecho($x); // foobar
function myecho($x) {
echo !empty($x) ? $x : '';
}
This fits the bill of "only writing the variable once", but doesn't give you as much flexibility as the echo command does because this is a function that is using echo, so you can't do something like: myecho($x . ', '. $y)
(the argument is now always defined and not empty once it hits myecho()
) 这符合“只编写一次变量”的要求,但不会像echo命令那样提供灵活性,因为这是一个使用echo的函数,所以你不能做类似的事情:
myecho($x . ', '. $y)
(参数现在总是被定义,一旦它击中myecho()
就不是空的)
Yes, you can write a function: 是的,你可以编写一个函数:
function echoIfNotEmpty($val) {
if (!empty($val)) {
echo $val;
}
}
Usage: 用法:
echoIfNotEmpty($x);
Sure you can shorten the function name. 当然你可以缩短功能名称。
If you don't know, if the var is intialized you can also do: 如果您不知道,如果var是初始化的,您还可以:
function echoIfNotEmpty(&$val = null) {
if (!empty($val)) {
echo $val;
}
}
Most times we want do prefix and append something 大多数时候我们想要做前缀并追加一些东西
function echoIfNotEmpty(&$val = null, $prefix = '', $suffix = '') {
if (!empty($val)) {
echo $prefix . $val . $suffix;
}
}
echoIfNotEmpty($x, '<strong>', '</strong>');
Easy approach would be to define an helper function so: 简单的方法是定义辅助函数,以便:
function mEcho($someVariable) {
if(!empty($someVariable) echo $someVariable;
}
I'm not sure though if that's what you intended. 我不确定这是不是你想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.