未定义索引:将 cookie 值转换为变量时
问题
以下代码从“print $readerStatus”行产生此错误 -
未定义索引:readerStatus
代码
<?php
//Get Cookie Value
if (isset($_COOKIE['readerStatus'])) {
$readerStatus=$_COOKIE['readerStatus'];
} Else {
$readerStatus="Not Set";}
echo "The value of Cookie readerStatus is " . $_COOKIE['readerStatus'];
print $readerStatus;
?>
背景 目标很简单,如果设置了 cookie,我想将值传递到 Javascript。我的策略如下:
- 从 cookie 获取值
- 将变量设置为 cookie 的值
- 然后在 Javascript 中使用 php echo 来传输该值。
它按预期工作,但 Eclipse 给了我错误,所以我认为上面的代码有问题。
如果您能指出问题的可能根源,我将不胜感激。
谢谢
The problem
The following code produces this error from the line "print $readerStatus" -
Undefined index: readerStatus
Code
<?php
//Get Cookie Value
if (isset($_COOKIE['readerStatus'])) {
$readerStatus=$_COOKIE['readerStatus'];
} Else {
$readerStatus="Not Set";}
echo "The value of Cookie readerStatus is " . $_COOKIE['readerStatus'];
print $readerStatus;
?>
Background
The goal is simply that if a cookie is set I want to pass the value into a Javascript. My strategy is as follows:
- Get the value from the cookie
- Set a variable to the value of the cookie
- Then use a php echo inside of the Javascript to transfer the value.
It works as expected but Eclipse is giving me the error and so I assume there is something wrong with the above code.
I'd appreciate any pointers on possible sources of the problem.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这有效吗?
Is this working?
这是警告,而不是错误。但是,您可以使用 array_key_exists 跳过该错误。一般来说,我不喜欢 isset 进行此类检查。
This is a warning, not an error. However, you can skip the error by using array_key_exists. Generally, I'm not a fan of isset for this kind of checking.
有些 IDE 比 PHP 解析器本身更不宽容。话虽如此,运行代码时您是否收到任何错误或通知? PHP 中的变量是隐式声明的,因此未定义索引消息只是一个关于在数组元素不存在的情况下访问该数组元素的通知(可以忽略)。
如果您在像这样访问它之前检查它是否存在,那么应该不会有问题。
Some IDEs are less forgiving than the PHP parser itself. That being said, do you get any errors or notices when running the code? Variables in PHP are implicitly declared, so the undefined index message is simply a NOTICE (that can be ignored) regarding the accessing of an array element without it existing first.
If you check it exists prior to accessing it like this, you shouldn't have a problem.