如何避免isset()和empty() [英] How to avoid isset() and empty()

查看:83
本文介绍了如何避免isset()和empty()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个较旧的应用程序,它们在E_NOTICE错误级别上运行时会抛出很多"xyz未定义"和未定义偏移"消息,因为未使用isset()和consorts明确检查变量的存在.

I have several older applications that throw a lot of "xyz is undefined" and "undefined offset" messages when running on the E_NOTICE error level, because the existence of variables is not explicitly checked using isset() and consorts.

我正在考虑通过它们使它们与E_NOTICE兼容,因为有关丢失变量或偏移量的通知可能会节省生命,可能会获得一些较小的性能改进,并且总体而言,这是一种更清洁的方法.

I am considering working through them to make them E_NOTICE compatible, as notices about missing variables or offsets can be lifesavers, there may be some minor performance improvements to be gained, and it's overall the cleaner way.

但是,我不喜欢对我的代码造成数百个isset() empty()array_key_exists()的事情.它变得肿,可读性降低,而没有获得价值或意义上的任何东西.

However, I don't like what inflicting hundreds of isset() empty() and array_key_exists() s does to my code. It gets bloated, becomes less readable, without gaining anything in terms of value or meaning.

如何在不进行过多变量检查的情况下构造代码,同时又能与E_NOTICE兼容?

How can I structure my code without an excess of variable checks, while also being E_NOTICE compatible?

推荐答案

对于那些感兴趣的人,我已将该主题扩展为一小篇文章,该文章以结构更好的形式提供了以下信息:

For those interested, I have expanded this topic into a small article, which provides the below information in a somewhat better structured form: The Definitive Guide To PHP's isset And empty

恕我直言,您不仅应该考虑使应用程序与"E_NOTICE兼容",还应该对整个事情进行重组.在代码中有数百个点,这些点经常尝试使用不存在的变量,这听起来像是一个结构很差的程序.尝试访问不存在的变量永远不会发生,其他语言在编译时会对此表示沮丧. PHP允许您这样做的事实并不意味着您应该这样做.

IMHO you should think about not just making the app "E_NOTICE compatible", but restructuring the whole thing. Having hundreds of points in your code that regularly try to use non-existent variables sounds like a rather badly structured program. Trying to access non-existent variables should never ever happen, other languages balk at this at compile time. The fact that PHP allows you to do it doesn't mean you should.

这些警告可以帮助您 ,而不是使您烦恼.如果收到警告您正在尝试使用不存在的东西!" ,您的反应应为糟糕,我的问题,让我尽快解决." 您还如何分辨在未定义的情况下可以正常工作的变量" 可能导致严重错误的诚实错误代码之间的区别?这也是为什么您总是总是用错误报告进行开发的原因变成11 ,并继续插入您的代码,直到未发布单个NOTICE为止.关闭错误报告仅适用于生产环境,以防止信息泄漏,甚至在遇到错误代码的情况下也能提供更好的用户体验.

These warnings are there to help you, not to annoy you. If you get a warning "You're trying to work with something that doesn't exist!", your reaction should be "Oops, my bad, let me fix that ASAP." How else are you going to tell the difference between "variables that work just fine undefined" and honestly wrong code that may lead to serious errors? This is also the reason why you always, always, develop with error reporting turned to 11 and keep plugging away at your code until not a single NOTICE is issued. Turning error reporting off is for production environments only, to avoid information leakage and provide a better user experience even in the face of buggy code.

详细说明:

您总是在代码中的某个地方需要issetempty,减少它们出现的唯一方法是正确初始化变量.根据情况,有不同的方法可以做到这一点:

You will always need isset or empty somewhere in your code, the only way to reduce their occurrence is to initialize your variables properly. Depending on the situation there are different ways to do that:

函数参数:

function foo ($bar, $baz = null) { ... }

无需检查函数内部是否设置了$bar$baz,因为您只需对其进行设置,所有您需要担心的是它们的值是否为truefalse(或其他值) ).

There's no need to check whether $bar or $baz are set inside the function because you just set them, all you need to worry about is if their value evaluates to true or false (or whatever else).

任意位置的常规变量:

$foo = null;
$bar = $baz = 'default value';

在将要使用它们的代码块的顶部初始化变量.这样可以解决!isset问题,确保您的变量始终具有已知的默认值,使读者可以了解以下代码将要处理的内容,从而还可以作为一种自说明文件.

Initialize your variables at the top of a block of code in which you're going to use them. This solves the !isset problem, ensures that your variables always have a known default value, gives the reader an idea of what the following code will work on and thereby also serves as a sort of self-documentation.

数组:

$defaults = array('foo' => false, 'bar' => true, 'baz' => 'default value');
$values = array_merge($defaults, $incoming_array);

与上述相同,您正在使用默认值初始化数组,并使用实际值覆盖它们.

The same thing as above, you're initializing the array with default values and overwrite them with actual values.

在其余情况下,假设您要在模板中输出可能由控制器设置或可能未设置的值,则只需检查以下内容即可:

In the remaining cases, let's say a template where you're outputting values that may or may not be set by a controller, you'll just have to check:

<table>
    <?php if (!empty($foo) && is_array($foo)) : ?>
        <?php foreach ($foo as $bar) : ?>
            <tr>...</tr>
        <?php endforeach; ?>
    <?php else : ?>
        <tr><td>No Foo!</td></tr>
    <?php endif; ?>
</table>

如果您经常使用array_key_exists,则应评估其用途.唯一的改变是在这里:

If you find yourself regularly using array_key_exists, you should evaluate what you're using it for. The only time it makes a difference is here:

$array = array('key' => null);
isset($array['key']); // false
array_key_exists('key', $array); // true

但是,如上所述,如果您正确初始化变量,则无需检查键是否存在,因为您知道它确实存在.如果您是从外部来源获取数组,则该值很可能不是null,而是''0'0'false或类似的值,即可以用来评估的值issetempty,取决于您的意图.如果您定期将数组键设置为null,并希望它表示除false以外的任何值,即,如果在上面的示例中,issetarray_key_exists的不同结果对您的程序逻辑有所不同,则应询问你自己为什么.仅仅存在一个变量并不重要,只有变量的值才有意义.如果键是true/false标志,则使用truefalse,而不是null.唯一的例外是希望null表示某些含义的第三方库,但是由于null很难在PHP中检测到,因此我尚未找到任何执行此操作的库.

As stated above though, if you're properly initializing your variables, you don't need to check if the key exists or not, because you know it does. If you're getting the array from an external source, the value will most likely not be null but '', 0, '0', false or something like it, i.e. a value you can evaluate with isset or empty, depending on your intent. If you regularly set an array key to null and want it to mean anything but false, i.e. if in the above example the differing results of isset and array_key_exists make a difference to your program logic, you should ask yourself why. The mere existence of a variable shouldn't be important, only its value should be of consequence. If the key is a true/false flag, then use true or false, not null. The only exception to this would be 3rd party libraries that want null to mean something, but since null is so hard to detect in PHP I have yet to find any library that does this.

这篇关于如何避免isset()和empty()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆