Run
Run

Reputation: 57176

php objects: property Object Vs stdClass Object - which one is better?

Sometimes I use __get or stdClass to convert arrays to object. But I can't decide I should stick to. I wonder which one is better and faster, any ideas?

class property 
{

    public function __get($name)
    {
        return (isset($this->$name)) ? $this->$name : null;
    }
}

$object = new property();
$object = new stdClass();

so if I use new property(), I will have a property object output,

property Object
(
....
)

while if I use new stdClass(), I will have a stdClass object output,

stdClass Object
(
....
)

so I can get the object data like this $item->title.

EDIT:

how I do the actual array to object conversion.

public function array_to_object($array = array(), $property_overloading = false)
    {

        # If $array is not an array, let's make it array with one value of former $array.
        if (!is_array($array)) return $array;

        # Use property overloading to handle inaccessible properties, if overloading is set to be true.
        # Else use std object.
        if($property_overloading === true) $object = new property();
            else $object = new stdClass();

        foreach($array as $key => $value)
        {
            $key = (string) $key ;
            $object->$key = is_array($value) ? self::array_to_object($value, $property_overloading) : $value;
        }

        return $object;
    }

Upvotes: 3

Views: 879

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173532

First off, an (almost) empty class definition like you have is almost like an stdClass so there won't be any major issues by using either.

That said, one advantage your "named" class has over stdClass is that you can define what happens when a non-existent property is being accessed by taking advantage of the __get magic method.

class property
{
   public function __get($name)
   {
       return null;
   }
}

The above is a simpler rewrite of your original property class; when __get() is being called, you already know that $this->$name is not set. Although this won't cause a notice, it doesn't prevent a fatal error when you try to reference $obj->bla->bla where $obj->bla doesn't exist.

It might be more useful to throw an exception when a non-existent property is being accessed:

class property
{
   public function __get($name)
   {
       throw new Exception("Property $name is not defined");
   }
}

This allows your code to catch the exception before it turns into a fatal runtime error that stops your script altogether.

Upvotes: 3

David Müller
David Müller

Reputation: 5351

If you just use your "property" class as a dumb data container, take stdClass or even an array.

Upvotes: 0

Related Questions