更正PHP代码以检查变量是否存在 [英] Correct PHP code to check if a variable exists

查看:110
本文介绍了更正PHP代码以检查变量是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码是websocket服务器的一部分:

This code is part of a websocket server:

$msgArray = json_decode($msg);
if ($msgArray->sciID) {
  echo "Has sciID";
}

它将接收一个像{"sciID":67812343}这样的json字符串,或者是一个没有sciID的完全不同的json字符串,例如{"something":"else"}.

It will either be receiving a json string like {"sciID":67812343} or a completely different json string with no sciID such as {"something":"else"}.

服务器收到以后的消息时,它会回显:Notice: Undefined property: stdClass::$sciID in /path/to/file.php on line 10

When the server receives the later, it echos out: Notice: Undefined property: stdClass::$sciID in /path/to/file.php on line 10

检查$msgArray->sciID是否存在的正确代码是什么?

What is the correct code to check if $msgArray->sciID exists?

推荐答案

isset 用作常规用途的检查(您也可以使用 property_exists ,因为您正在处理一个对象):

Use isset as a general purpose check (you could also use property_exists since you're dealing with an object):

if (isset($msgArray->sciID)) {
    echo "Has sciID";
}

这篇关于更正PHP代码以检查变量是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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