Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in PHP correct solution for String offset cast occurred

Tags:

string

php

on the following functions, I get the error

'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) "Ç"
}

As of PHP 5.4 string offsets have to either be integers or integer-like strings, otherwise a warning will be thrown.

Is the correct solution is to cast to integer like this

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

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

like image 377
LeMoussel Avatar asked Apr 10 '26 00:04

LeMoussel


1 Answers

The solution is to cast $char to an int; although a double has the same value, PHP explicitly expects ints since 5.4. The fix is to have position2CharAndByte return an int instead of a double, casting it in the caller of position2CharAndByte requires unnecessary code duplication. (*cough*fixed*cough*).

like image 91
deceze Avatar answered Apr 12 '26 13:04

deceze