1

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 Answers 2

9

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
Sign up to request clarification or add additional context in comments.

2 Comments

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 has the best solution for what you want.
2

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.

2 Comments

I concur, would not advise trying to do this. Stick with $image['default'] and keep it an array.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.