tags:

views:

67

answers:

2

Hey all,

I'm just wondering if its possible to have something like this:

$image = array(

"default" => "test.jpg",
"width" => 400,
"height" => 500

);

Then you could call:

echo $image // test.jpg
echo $image['width'] // 400

Thanks, Matt Mueller

+2  A: 

Simple answer: No, that's not possible. The only thing that's somewhat similar is using PHP's weak type system and assigning the default value to the array as string until you initialize the array - but I'm not sure that's what you want.

Franz
I concur, would not advise trying to do this. Stick with `$image['default']` and keep it an array.
meder
Well, that doesn't really matter anyways, since what Matt wants to do isn't possible - having returned the value of the `default` key when just calling the array.
Franz
+8  A: 

No, image is an array so it will echo array()

You can however do this with __toString

class image {

    private $defaultImage = 'test.jpg';

    function __toString() {
     return $this->defaultImage;
    }

}

$image = new image;
$image->height = 400;

echo $image; // test.jpg
echo $image->height; //400
Galen
+1 was about to post this.
thephpdeveloper
Good idea. Would it even be possible to create a subclass of `ArrayObject` which reads the string for `__toString()` from the array field with the key `default`?
Franz
Franz has the best solution for what you want.
Chris