[英]Can I use PHP try/catch around a large block of HTML?
I would like to surround this entire block of code in a try/catch since its causing an error when there is nothing in the grid array. 我想将整个代码块放在try / catch中,因为当网格数组中没有内容时,它会导致错误。 Whats the best way to do this?
最好的方法是什么?
<?php foreach ($grid->result() as $idx => $row): ?> <?php if ($idx % 3 == 2): ?>
<div class="img_grid_3"><img src="/images/thumb/<?= $row->images_name; ?>" /></div>
<?php else: ?>
<div class="img_grid"><img src="/images/thumb/<?= $row->images_name; ?>" /></div>
<?php endif; ?>
<?php endforeach; ?>
Thanks 谢谢
Maybe Im missing the point but why dont you test $grid before doing the foreach? 也许我错过了重点,但是为什么在进行foreach之前不测试$ grid?
<?php if($grid): ?>
.... foreach ....
<?php endif; ?>
If I got you right, you're looking for the @
error suppression operator. 如果我说对了,那么您正在寻找
@
错误抑制运算符。 If you pass an empty array to foreach, you'll get a PHP warning, you can't catch this with a try/catch
block. 如果将空数组传递给foreach,则会收到PHP警告,您无法使用
try/catch
块来try/catch
。
<?php @foreach ($grid->result() as $idx => $row): ?>
<?php if ($idx % 3 == 2): ?>
<div class="img_grid_3"><img src="/images/thumb/<?= $row->images_name; ?>" /></div>
<?php else: ?>
<div class="img_grid"><img src="/images/thumb/<?= $row->images_name; ?>" /></div>
<?php endif; ?>
<?php endforeach; ?>
It's possible to use a try catch block with html contents too, but it will obviously only catch Exceptions
. 也可以对HTML内容使用try catch块,但是显然只能捕获
Exceptions
。
Note that it's cleaner to check wheter the array is empty or not before you use it in a foreach
block. 请注意,在
foreach
块中使用数组之前,检查数组是否为空是比较干净的。
foreach
will not produce an error if the array is empty. 如果数组为空,则
foreach
不会产生错误。
So either $grid
is not an object, or result()
is returning a non-array like false
or null
. 因此,要么
$grid
不是对象,要么result()
返回一个非数组,如false
或null
。 If the former, surround the foreach
with if ($grid)
, of the latter, than use if (!empty($grid->result()))
如果是前者,则用后者的
if ($grid)
包围foreach
,而不是使用if (!empty($grid->result()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.