我应该声明并检查PHP中是否存在变量吗? [英] Should I declare and check if variables exist in PHP?

查看:54
本文介绍了我应该声明并检查PHP中是否存在变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在XAMPP上注意到严格的错误报告功能已经打开,现在我得到未定义的索引错误.我只有两个小问题(我仍在这里学习):

I've noticed on XAMPP that strict error reporting is on and I get undefined index errors now. I just have two small questions (I'm still learning here):

我知道您没有没有在PHP中声明变量,但是无论如何声明它们有什么好处吗?如果没有,为什么在未定义严格错误报告时出现错误?

I know you don't have to declare variables in PHP but is there any advantage to declaring them anyway? If not, why do I get errors when strict error reporting is on when I don't define them?

例如,当我使用get变量时,我先检查它们的值,然后再运行类似的函数

When I use get variables for example, I check for their value before I run a function like

if($_GET['todo'] == 'adduser')
    runFunctionAddUser();

这会导致错误,因为我从不检查get变量是否首先存在.我该怎么办

This gives an error because I never check if the get variable exists first. Should I do

if(isset($_GET['todo']))
    if($_GET['todo'] == 'adduser')
        runFunctionAddUser();

而不是?这样做有好处吗?还是不必要且缓慢?

instead? Would there be an advantage to this or would it be unnecessary and slow?

推荐答案

该线程有点旧,但是我做了一些与该问题有关的测试,所以我不妨发布它:

This thread is abit old but I did some tests relating to the question so I might as well post it:

测试代码(PHP 5.3.3-CentOS版本6.5(最终版)):

The testing code (PHP 5.3.3 - CentOS release 6.5 (Final)):

class NonExistant
{
    protected $associativeArray = array(
        'one' => 'one',
        'two' => 'two',
        'three' => 'three',
        'four' => 'four',
        'five' => 'five',
        'six' => 'six',
    );

    protected $numIterations = 10000;

    public function noCheckingTest()
    {
        for ($i = 0; $i < $this->numIterations; $i++) {
            $this->associativeArray['none'];
        }
    }

    public function emptyTest()
    {
        for ($i = 0; $i < $this->numIterations; $i++) {
            empty($this->associativeArray['none']);
        }
    }

    public function isnullTest()
    {
        for ($i = 0; $i < $this->numIterations; $i++) {
            is_null($this->associativeArray['none']);
        }
    }


    public function issetTest()
    {
        for ($i = 0; $i < $this->numIterations; $i++) {
            isset($this->associativeArray['none']);
        }
    }

    public function arrayKeyExistsTest()
    {
        for ($i = 0; $i < $this->numIterations; $i++) {
            array_key_exists('none', $this->associativeArray);
        }
    }
}

结果是:

| Method Name                              | Run time             | Difference
=========================================================================================
| NonExistant::noCheckingTest()            | 0.86004090309143     | +18491.315775911%
| NonExistant::emptyTest()                 | 0.0046701431274414   | +0.95346080503016%
| NonExistant::isnullTest()                | 0.88424181938171     | +19014.461681183%
| NonExistant::issetTest()                 | 0.0046260356903076   | Fastest
| NonExistant::arrayKeyExistsTest()        | 1.9001779556274      | +209.73055713%

通过call_user_func()以相同的方式调用所有函数,并以microtime(true)

All the functions are called the same way with via call_user_func() and timed with microtime(true)

观察

empty()isset()是这里其他两种方法的明显赢家,这两种方法在性能上有很大的联系.

empty() and isset() are the clear winners over the other 2 methods here, the two methods are pretty much tied on performance.

is_null()之所以表现不佳,是因为它需要首先查找该值,这与访问不存在的值$this->associativeArray['none']几乎相同,后者涉及对数组的完整查找.

is_null() performs bad because it needs to lookup the value first, pretty much the same as just accessing the non-existant value $this->associativeArray['none'], which involves a full lookup of the array.

但是,array_key_exists()的性能令我感到惊讶.它比empty()isset()慢2倍.

However, i'm surprised by the performance of array_key_exists(). Where it is 2 times slower than empty() and isset().

注意:

我测试过的所有功能都有不同的用途,此基准仅适用于您要快速检查数组中值的最通用的用例.我们可以讨论是否应该将null视为值"还是仅仅是不存在的指示符,但这是另一个主题. o.o

All the functions I've tested have different uses, this benchmark is only here for the most generic use case where you want to quickly check the value in an array. We can go into argument of whether null should be considered a "value" or simply an indicator of non-existence, but that's another topic. o.o

更新2017年1月20日

使用PHP 7.1

修复了@bstoney提到的错误

Fixed bug mentioned by @bstoney

$ php -v
PHP 7.1.0 (cli) (built: Dec  2 2016 03:30:24) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.1.0-dev, Copyright (c) 1998-2016 Zend Technologies
$ php -a
php > $a = ['one' => 1, 'two' => 2, 'three' => 3];
php > $numIterations = 1000000;
php > $start = microtime(true); for ($i = 0; $i < $numIterations; $i++) { $a['none']; }; echo microtime(true) - $start;
0.43768811225891
php > $start = microtime(true); for ($i = 0; $i < $numIterations; $i++) { empty($a['none']); }; echo microtime(true) - $start;
0.033049821853638
php > $start = microtime(true); for ($i = 0; $i < $numIterations; $i++) { is_null($a['none']); }; echo microtime(true) - $start;
0.43995404243469
php > $start = microtime(true); for ($i = 0; $i < $numIterations; $i++) { isset($a['none']); }; echo microtime(true) - $start;
0.027907848358154
php > $start = microtime(true); for ($i = 0; $i < $numIterations; $i++) { array_key_exists('none', $a); }; echo microtime(true) - $start;
0.049405097961426

这篇关于我应该声明并检查PHP中是否存在变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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