drwpbrv668670 2017-02-15 23:15
浏览 94
已采纳

如何在PHP中正确比较字符串和整数?

I purchased a Drupal theme and the the support is...lacking. So I thought I'd try and tackle it myself. I'm relatively new to PHP programming, so please take it easy on me :)

The error I got was: Notice: Object of class Drupal\Core\Field\FieldItemList could not be converted to int in theme_css_alter()

Digging into the error, it came from the first line of code in this if statement:

if(isset($node->nid) && $node->nid == 90){
    //do stuff
 }

I did my research and found that its a PHP error when using the == operator, likely since $node->nid is being fetched as a string, and 90 is an integer, and it can't convert the nid on the fly.

Possible solutions I found while Googling were either making a 'getter' to fetch the nid as an integer (which sounds more complicated than necessary), using the === operator; and I'm guessing on my own that if I convert 90 to a string it would also work?

Now, doing a test run, === does stop the error from showing, but my research shows that === only works when both the value and type are equal, and given I'm comparing a string and an integer, I assume that it would always just be false then.

So...

  1. Am I correct in saying that in PHP 90 (as a string) does not == 90 (as an integer)?
  2. Am I correct in saying that using === instead of == is NOT the correct way to compare a string and integer?
  3. Would $node->nid == (string)90{ be the correct way to compare for this if statement? What is the most correct way to do this comparison?
  • 写回答

3条回答 默认 最新

  • dshdb64088 2017-02-15 23:26
    关注

    When you compare a number with something else, the other thing is first converted to a number, and then these two numbers are compared. So a comparison like "90" == 90 does what you expect -- it's equivalent to 90 == 90.

    The problem you're having is that $node->nid is not a string, it's an object of class Drupal\Core\Field\FieldItemList. The class doesn't provide a method to convert this type to a number, so it's not able to perform the comparison.

    However, it appears that this type has a method to convert to string. But PHP won't do a double conversion when performing the comparison. So you need to perform the object->string conversion explicitly, and then PHP will convert the string to an integer.

    if (isset($node->nid) && (string)$node->nid == 90)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化