0

I have a own Array class. Like this:

myArray::fetch('site.meta.keywords');  // return Array(...)

At the same time, How can I do like this?

myArray::fetch('site.meta.keywords');                // return Array(...)
myArray::fetch('site.meta.keywords')->as_object();   // return Object{...}

Is it possible in PHP?

3 Answers 3

2

You can't because an array doesn't have an as_object method. I would make a separate fetchAsObject method in your array class, or introduce an optional asObject parameter (boolean, default false) to your existing fetch method.

Sign up to request clarification or add additional context in comments.

Comments

0

You should take a look at ArrayObject, it behaves the same as any other array and you can extend it (or your class?).

In your case I'd return something like MyArrayObject (your class extending ArrayObject with method as_object() etc.).

Comments

0

If in first case you are returning raw PHP Array it is not possible. You can do that way:

public static function fetch($key, $as_object = false) 
{
    //in $data you have your array
    return ($as_object) ? (object)$data : $data; 
}

myArray::fetch('site.meta.keywords');  //return array
myArray::fetch('site.meta.keywords', true);  //return object

Or just simply like that:

$dataAsArray = myArray::fetch('site.meta.keywords');
$dataAsObject = (object)myArray::fetch('site.meta.keywords');

4 Comments

If it were possible, wouldn't it be nice? :)
Like I said, when you want to return raw PHP array it isn't possible. But with little code (extending ArrayObject) and adding method as_object it could be done. But why, when you can cast array to object -> look edited version of my answer.
alright, multi-dimensional arrays? The casting array to object will not good practice in multi-dimensional array. In this case, inner arrays remain still as array.
Yes - my solution from answer will work for one dimensional arrays. If you want multiple, first part of my previous comment will be an answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.