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条)

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。