Search code examples
phpobjectphp-5.2interpreted-languageloose-typing

PHP class method treats parameter as an object instead of string/dynamically interpreting the parameter data type


I discovered something new today.

I have a PHP class with typical members, private, public and protected methods.

One of the methods is this:

protected function processThis($dataString)
{
   $dataStringJson = json_decode($dataString);

}

And this spits out a warning:

json_decode() expects parameter 1 to be string, object given in .../File.php on line xxx

Wait a second, isn't PHP loosely typed and dynamically interpreted ?


Solution

  • Sure it is, but there are some functions where it is better to alert people that they are doing something odd. You'll also get warnings for $f = "1"; array_shift($f);.

    If you want json_decode to just work, then casting to a string is easy enough:

    protected function processThis($dataString)
    {
       $dataStringJson = json_decode(''.$dataString);
    }