采用这一行PHP:
$foo["bar"] = 1;
如果$foo
不存在,我希望PHP抛出异常。现在,即使将display_errors
设置为1并使用error_reporting
调用E_ALL
,它也不会抛出异常,甚至不会打印错误或警告。相反,它会创建一个数组$foo
并将$foo["bar"]
设置为1
,即使事先不存在变量$foo
。
是否有类似declare(strict_types=1);
的内容可以检查此内容?
我想要这个的原因是,当我不小心拼错一个变量名时,我可以更容易地发现错别字。
答案 0 :(得分:5)
不幸的是,您正在使用该命令设置数组。如果要设置这个,为什么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在您的示例中抛出异常或打印警告。
答案 1 :(得分:0)
以下是错误报告的小例子:
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
在PHP $bar=1
中,它只是一个字符串,在您的情况下,您声明了一个类似$bar['foo']=1
的数组。在这种情况下,您可以在此之前启动您不需要提供的数组。
答案 2 :(得分:-2)
足够接近? 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注意到未设置的区别,并设置为NULL。
答案 3 :(得分:-2)
你可以在任何地方和任何地方抛出异常: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
开头