php - 在 PHP 中,发生 String offset cast 的正确解决方案

标签 php string

在下面的函数中,我得到了错误

'String offset cast occured'

protected function setBitAtPosition($pos) {
    list($char, $byte) = $this->position2CharAndByte($pos);
    // Error Notice :  String offset cast occurred in ....
    $this->bitField[$char] = $this->bitField[$char] | $byte;
}

protected function getBitAtPosition($pos) {
    list($char, $byte) = $this->position2CharAndByte($pos);
    // Error Notice :  String offset cast occurred in ....
    return ($this->bitField[$char] & $byte) === $byte;
}


var_dump($this->position2CharAndByte($pos));
array(2) {
  [0] =>
  double(9552303)
  [1] =>
  string(1) "Ç"
}

从 PHP 5.4 开始,字符串偏移量必须是整数或类似整数的字符串,否则将引发警告。

正确的解决方案是像这样转换为整数吗

$this->bitField[(int)$char] = $this->bitField[(int)$char] | $byte;

return ($this->bitField[(int)$char] & $byte) === $byte;

最佳答案

解决方案是将$char 转换为int;虽然 double 具有相同的值,但自 5.4 起,PHP 明确要求使用整数。解决方法是让 position2CharAndByte 返回一个 int 而不是 double,将其转换为 position2CharAndByte 的调用者需要不必要的代码重复。 (*咳嗽* fixed *咳嗽*)。

关于php - 在 PHP 中,发生 String offset cast 的正确解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36951865/

相关文章:

php - 按相关性进行 boolean 全文搜索顺序似乎不起作用

string - 限制字符串长度并在截断时添加 "..."

string - Spark Scala 进行部分字符串计数的最有效方法

c++ - 为什么在使用字符索引数组时会出现这种不同的行为?

php - 发送邮件会在 "to:"电子邮件列表中的第 995 个字符处插入一个随机空格

php - 基于概率从PHP数组中选择随机项目

php - 无论我调用 "commands out of sync"多少次,mysqli 都会出现 "next_result()"错误

php - php中isset()和empty()的区别

javascript - 根据另一个选择下拉列表中选择的年份动态显示选择下拉列表中剩余的可用月份

无法在打印超过 80 个字符的输入行的程序中找到错误