简体   繁体   English

的PHP:如果属性不存在

[英]php: if property doesn't exist

I just encountered a problem which is new to me and I found 2 solutions... this question is basically about finding a better or cleaner one if there is ! 我刚刚遇到了一个新问题,我找到了2个解决方案...这个问题基本上是关于找到更好或更清洁的解决方案!

In my DB, I store some preferences for every user about his daily schedule. 在我的数据库中,我为每个用户存储一些有关他的日程安排的首选项。 The first time the user connects, the DB doesn't have any infos so I'm running this code: 用户第一次连接时,数据库没有任何信息,因此我正在运行以下代码:

if(!empty($opening_h->{'lunch'}) == true) 
{ 
    if($opening_h->{'lunch'} == 1) 
    {
        echo 'checked';
    };
};

PS: there are multiple values in there, encoded in json format. PS:其中存在多个以json格式编码的值。

Is there a better way? 有没有更好的办法? The other one I could think about would be to write 我能想到的另一件事是写

lunch => 0, dinner => 0

when the user registers to the platform... but that seems silly. 当用户注册到平台时...但这似乎很愚蠢。

Thanks for your help! 谢谢你的帮助!

I would recommend using __isset magic method in your class for $opening_h to check whether the property exists first and to do something if not. 我建议在您的类中为$ opening_h使用__isset magic方法,以检查该属性是否首先存在,如果不存在,请执行某些操作。 Then, when you're sure your property exists, you can easily write something like: 然后,当您确定自己的财产存在时,可以轻松编写如下内容:

if($opening_h->{'lunch'} == 1) {
    echo 'checked';
};

With the __isset now it looks simpler. 现在使用__isset看起来更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM