代码之家  ›  专栏  ›  技术社区  ›  Flimm D. Ben Knoble

$foo[“bar”]=1;如果$foo不存在,我可以让PHP投诉吗?

php
  •  2
  • Flimm D. Ben Knoble  · 技术社区  · 8 年前

    以这行PHP为例:

    $foo["bar"] = 1;
    

    $foo 不存在。现在,它不会抛出异常,甚至不会打印错误或警告,即使 display_errors error_reporting 呼叫人 E_ALL $foo 和集合 $foo["bar"] 1 ,即使变量 事先不存在。

    有这样的东西吗 declare(strict_types=1);

    我之所以要这样做,是因为当我意外拼错变量名时,我可以更容易地检测到拼写错误。

    4 回复  |  直到 8 年前
        1
  •  5
  •   Flimm D. Ben Knoble    8 年前

    不幸的是,您正在使用命令设置数组。如果您正在设置,为什么php会抛出异常?

    这就像给变量赋值,然后问PHP为什么要给变量赋值?

    $foo["bar"] = 1;
    
    print_r($foo);
    // This prints the following: 
    // Array ( [bar] => 1 )
    

    if(isset($foo))
    {
      $foo['bar'] = 1;
    }
    else
    {
      // do something if $foo does not exist or is null
    }
    

    希望这有帮助!简而言之,您的问题的答案是否定的:没有办法让PHP在您的示例中引发异常或打印警告。

        2
  •  0
  •   Nawin    8 年前

    下面是我的错误报告小示例:

    error_reporting(E_ALL);
    
    $foo = $bar; //notice : $bar uninitialized
    
    $bar['foo'] = 'hello'; // no notice, although $bar itself has never been initialized (with "$bar = array()" for example)
    
    $bar = array('foobar' => 'barfoo');
    $foo = $bar['foobar'] // ok
    
    $foo = $bar['nope'] // notice : no such index
    

    $bar=1 它只是一个字符串,在您的示例中,您声明了一个数组,如 $bar['foo']=1 。在这种情况下,您启动了在此之前不需要给出的数组。

        3
  •  -2
  •   hanshenrik    8 年前

    if(!isset($foo)){throw new Exception('$foo is not set!');}

    如果未设置$foo,或者$foo为NULL,则会引发异常。

    if(!array_key_exists('foo',get_defined_vars())){throw new Exception('$foo is not set!');}

    如果未设置$foo,则会引发异常。与isset()不同,这个1注意到了not set和set为NULL之间的区别。

        4
  •  -2
  •   Arnas Veberis    8 年前

    您可以在任何地方抛出异常:D请记住,不一定推荐使用can:D

    try 阻止和 caught 如果你想处理它。

    升级@veggito代码以满足您的需求如下所示:

    try {
        if(isset($foo))
            $foo['bar'] = 1;
        else
            throw new Exception('Seems like $foo is not set');
    } catch (Exception $e)
      // do something with the exception, like $e->getMessage() and etc, or execute any code you wish
    }
    

    阅读更多关于例外的信息,网上有很多信息,可能从 http://php.net/manual/en/language.exceptions.php

    推荐文章