Web Hosting Talk







View Full Version : Php question


Froggy
11-05-2005, 07:45 AM
I noticed something that I take as odd behavior for php (I'm using php 5.0.5), say you have a class:

class Blah {
private $name;

function __contruct($name){ $this->name = $name; }

function getName(){ return $this->name; }
}

Now lets say you have an array (call it $array) and you do this:
$blah = new Blah();
$array[$blah->getName()] = $blah;

If you do this you get an "Illegal Offset type" error, where as if you caste the $blah->getName() to string if works fine....anybody know why this is the case? I would figure php would automatically do this...

Burhan
11-05-2005, 08:08 AM
This might be because PHP 5 provides a __toString() method, which is used when a string cast is required of an object type. In older PHP versions, an object cast to a string simply returned "Object".

However, array offsets can only be integer or string types, so if you pass it an object, it will give you illegal offset type.

Might also be resolved in newer versions of PHP5 -- I haven't been keeping up with all the latest developments regarding PHP5

bigfan
11-05-2005, 10:43 AM
With the code you posted, on v.5.0.5 and an "echo" line (below) added, this is displayed:Warning: Missing argument 1 for Blah::__construct() in C:\htdocs\test_11_05.php on line 7
=>Object id #1With this code:$blah = new Blah('Orville');
$array[$blah->getName()] = $blah;
echo $blah->getName() . '=>' . $array[$blah->getName()];this is displayed:Orville=>Object id #1Both are expected behavior, AFAIK.

The magic method "__toString" can be added to the class, but it ...will only be called when it is directly combined with echo() or print().and so wouldn't change anything.