tags:

views:

48

answers:

3

I was aware of (int) and (array) but not (object) and probably others.

I'm wondering a) what is the proper name of those "things"; and, b) where can we found more information about those? (I was unable to find (object) on php.net website.

Thanks in advance, MEM

+5  A: 

It's called type casting/conversion.
see http://docs.php.net/language.types.type-juggling#language.types.typecasting

VolkerK
@Stephen: Thanks for that add on. I was actually not aware of primitives and objects and their differences. ;)
MEM
@VolkerK - Exactly what I was asking for. Thanks a lot.
MEM
A: 

PHP has not a typezation; And this "things" set hard the type of variables.

Alexander.Plutov
Not true. Loose typing doesn't mean there isn't a type system. There's also conversion involved in `$x=(bool)'0'`, it's not just setting the type (which btw would be hard to set if there weren't a typesystem ;-)).
VolkerK
A: 

Be very careful!

If you try something like

$array = array(5, 2, 3);
$object = (object)$array;
print_r($object);
echo $object->2;

you'll end up with

PHP Parse error:  syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$' in - on line 5

Really, the safest way to convert from arrays to objects is pretty convoluted but works alright:

public function makeObjects($data)
{
    $object = (object) $data;
    foreach ($object as $property)
    {
        if (is_array($property)) $this->makeObjects($property);
    }

    return $object;
}
hopeseekr
Ummm... `$object = (object) $array` works quite fine... The reason for your fatal error is because `$object->2` is not a valid syntax. It's not related to the conversion...
ircmaxell
as far as I can see the code inside the foreach does nothing meaningful
Tom Haigh
Used:$response = (object) array( 'success' => TRUE, 'data' => array(1, 2, 3));No issues there. ;)
MEM
@Tom Haigh: Um, it converts nested arrays into nested objects. How is that not useful?
hopeseekr
@hopeseekr: the bit inside the foreach doesn't do anything with the return value of makeObjects()
Tom Haigh