21

Im starting to move away from using arrays in PHP as objects are so much neater and in php 5 there is no performance hits when using objects.

Currently the way I do it is:

$object = (object) array('this' => 'that', 'foo' => (object) array('bar' => 123));

However, i find it so tedious to have to typecast every time as typecasting isnt recursive...

Is there any way in php (or will there be) to do it like this or something similar:

$object = {
    'this' => 'that',
    'foo' => {
        'bar' => 123
    }
};
5
  • 5
    Why do you want to use an object when you create it as an array anyways? Commented Nov 16, 2012 at 13:00
  • I can not understand your need to cast it in that way. Commented Nov 16, 2012 at 13:06
  • 1
    you could upgrade to php 5.4 and use the short array syntax; that'll make your code neater. I'm with @DainisAbols though; I'm not certain what you're trying to achieve with the type casting anyway. What advantage do you see of using objects over arrays in this context? Commented Nov 16, 2012 at 13:08
  • 1
    What is "so much neater" about objects? Using them, you're missing out on a host of array functions you can apply. If you'd use custom classes with type hinting, then I'd agree. But I see no advantage to regular stdClass objects. Commented Nov 16, 2012 at 13:11
  • There might just be a slight performance hit when casting Everything to object all the time, what have you done to test this, have you actually tried this with substantial amounts of data, like a sizeable SQL result-set? Commented Nov 16, 2012 at 13:31

6 Answers 6

48

Starting from PHP 5.4 short array syntax has become available. This allows you to initialize array like this:

$myArray = ["propertyA" => 1, "propertyB" => 2];

There is no currently short object syntax in PHP as of PHP 8.2. But you can cast short array syntax to create objects like this:

$object = (object) [
    'this' => 'that',
    'foo' => (object) [
        'bar' => 123
    ]
];

Looks much nicer and shorter than using the following construct:

$object = new \StdClass();
$object->this = 'that';
$object->foo = \StdClass();
$object->foo->bar = 123;
Sign up to request clarification or add additional context in comments.

Comments

5

I recommend you to build a function width StdClass.

function arrayToObject($array) {
    if(!is_array($array)) {
        return $array;
    }

    $object = new stdClass();
    if (is_array($array) && count($array) > 0) {
      foreach ($array as $name=>$value) {
         $name = strtolower(trim($name));
         if (!empty($name)) {
            $object->$name = arrayToObject($value);
         }
      }
      return $object;
    }
    else {
      return FALSE;
    }
}

Comments

3

PHP does not currently support short object syntax. As of PHP 5.4 they support short array syntax. Maybe 5.5 will include what you are after.

As an alternative:

You could craft your objects as JSON and use json_decode():

$json = '{"this": "that", "foo": {"bar": 123}}';
var_dump(json_decode($json));

Note: I am only showing this as demonstration of a way to solve your question. I am not advocating such a practice.

3 Comments

correct code would be $json = '{"this" : "that", "foo": {"bar": 123}}';
Thanks. Mixed a little array syntax in there :)
nice answer, I would change it to a herestring like <<<JSON JSON; just to avoid quote hell
2

I have an alternative solution for when you receive an already built array. Say your array has n nested arrays so you have no chance of casting each one in a simple way. This would do the trick:

$object = json_decode(json_encode($unknownArray));

I would not use this in a large loop or something similar, as it is way slower than just sticking with the array sintax and live with it. Also, if an element of the array is a function or some other funny thing this would break that.

Example usage:

$unknownArray = array(
    'a' => '1',
    'b' => '2',
    'c' => '3',
    'd' => array(
        'x' => '7',
        'y' => '8',
        'z' => '9',
    ),
);
$object = json_decode(json_encode($unknownArray));
echo $object->d->x;

Comments

0

Unfortunately there's no syntax creating stdClass instances like that. But you could use the new keyword and any of the spl classes (not much tidier i admit). If you want to optimize for keystrokes, you could write a little helper function like this:

function O($a){
    return new ArrayObject($a); // has -> and [] support too
}

and write

$stuff = O(array('a' => 'tickle me elmo', 'b' => O(array('foo' => 'bar'))));

Comments

0

Though I honestly can't see why you'd want to do this (associative arrays are in essence data-only-objects) but if you insist:
Instead of casting every single array, on every single level to an object, you could use the following "trick/hack":

$object = json_decode(
              json_encode(
                   array('some'=>array('multi'=>'Dimensional'),
                         'array'=>'that',
                         'you' => array('want' => 'to',
                                        'turn' => 'into'),
                         'an' => 'object')));

This converts all arrays into instances of the stdClass, which I believe is what you wanted.
Again, I have to say: PHP is not JavaScript, and objects are far more expensive (relatively speaking) in languages like PHP, then they are in JS. I'd strongly recommend you stick with using assoc arrays if you don't need an object.

Like objects, arrays can be type-hinted: function foo (array $argument){}
If you really want to turn them into a particular instance of some class, why not change the constructor, to deal with an array:

class My_Object extends stdClass
{
    public function __construct(array $params = null)
    {
        if (!empty($params))
        {
            foreach ($params as $name => $value)
            {
                $this->{$name} = $value;//set everything
            }
        }
    }
}

And go on to add whatever methods you want to add to the lot

Comments

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.