When Should I Use Stdclass and When Should I Use an Array in PHP Oo Code

When should I use stdClass and when should I use an array in php oo code?

The usual approach is

  • Use objects when returning a defined data structure with fixed branches:

     $person
    -> name = "John"
    -> surname = "Miller"
    -> address = "123 Fake St"
  • Use arrays when returning a list:

      "John Miller"
    "Peter Miller"
    "Josh Swanson"
    "Harry Miller"
  • Use an array of objects when returning a list of structured information:

      $person[0]
    -> name = "John"
    -> surname = "Miller"
    -> address = "123 Fake St"

    $person[1]
    -> name = "Peter"
    -> surname = "Miller"
    -> address = "345 High St"

Objects are not suitable to hold lists of data, because you always need a key to address them. Arrays can fulfill both functions - hold arbitrary lists, and a data structure.

Therefore, you can use associative arrays over objects for the first and third examples if you want to. I'd say that's really just a question of style and preference.

@Deceze makes a number of good points on when to use an object (Validation, type checking and future methods).

stdClass vs array. Which is recommended?

There is a similar question What is better stdClass or (object) array to store related data? with this answer

Based on small test (http://phpfiddle.org/lite/code/cz0-hyf) I can say
that using "new stdClass()" is about 3 times slowlier than other
options.

It is strange, but casting an array is done very efficiently compared
to stdClass.

But this test meters only execution time. It does not meter memory.

P.S. I used phpFiddle only to share code. Test were done at my local
PC.

In answer to another similar question you can see this conclusion:

  1. For arrays, PHP 5.5 is faster than PHP 5.4, for object it is pretty much the same
  2. Class is slower than Arrays thanks to the optimization of PHP 5.5 and arrays.
  3. stdClass is evil.
  4. Class still uses less memory than Arrays. (about 30-40% less!!).
  5. SplFixedArray is similar to use a Class but it uses more memory.

When to use PHP stdClass

This is partly a matter of opinion, but personally I have never used stdClass, and I've never understood the point of doing so.

The purpose of an object is to encapsulate data and behaviour, whether that's by adding public and private methods to the object, using inheritance and polymorphism to structure your project, or just having a well-defined named type.

In some languages, e.g. JavaScript, an object is useful as a general-purpose key-value store, even if properties are added completely ad hoc; in PHP, that role can simply and effectively be filled by an associative array.

Some people will use stdClass objects as key-value stores, but they lose the use of all the functions around arrays by doing so. As ZubaiR points out above an object will be passed/assigned as a kind of pointer (not the same as passing a variable by reference) rather than being copied as necessary, so will behave differently, but if you're not deliberately using the "encapsulation" aspect of OOP (in which case you would probably create a class), it's hard to say if this is a good thing or just a chance for confusion.

In other languages, such as C, there is a way of defining custom "struct" types, with pre-defined named members. PHP has no such type, but a simple methodless class like the one you show is pretty close.

Another advantage in other languages that doesn't apply in PHP is that the base class for objects could have some functionality, or even - as in JavaScript or Ruby - allow you to add some functionality. In PHP, stdClass is completely inert and cannot be edited, and as pointed out elsewhere is not in fact used as a base class for other objects; it's only "magic" ability is to be the target class when something is cast or "juggled" to be of type object.

The immediate benefits of using a named class include:

  • the PHP engine, and tools such as IDEs and code sniffers, know which properties "should" exist, and can warn you if you set invalid ones, e.g. through a spelling mistake
  • you can check if a particular value passed is the right type of object (using instanceOf) rather than
  • you can easily expand the object later to have extra functionality, or make it part of an inheritance hierarchy, etc

stdClass Object In Array Iteration

This is easily enough done with array_column() to get the ID values; it works just as well with objects as it does with arrays.

<?php
// some sample data
$results = json_decode('[{"ID": 1}, {"ID": 2}, {"ID": 3}]');

$return = implode(",", array_column($results, "ID"));
echo $return;

Output:

1,2,3

What is stdClass in PHP?

stdClass is PHP's generic empty class, kind of like Object in Java or object in Python (Edit: but not actually used as universal base class; thanks @Ciaran for pointing this out).

It is useful for anonymous objects, dynamic properties, etc.

An easy way to consider the StdClass is as an alternative to associative array. See this example below that shows how json_decode() allows to get an StdClass instance or an associative array.
Also but not shown in this example, SoapClient::__soapCall returns an StdClass instance.

<?php
//Example with StdClass
$json = '{ "foo": "bar", "number": 42 }';
$stdInstance = json_decode($json);
echo $stdInstance->foo . PHP_EOL; //"bar"
echo $stdInstance->number . PHP_EOL; //42
//Example with associative array
$array = json_decode($json, true);
echo $array['foo'] . PHP_EOL; //"bar"
echo $array['number'] . PHP_EOL; //42

See Dynamic Properties in PHP and StdClass for more examples.

PHP stdClass Object with array inside

Ok so I just simplified the array... AND THAT WORKS!

//clean and make into an array
$response_Decode=$response_Decode->data;
$response_Decode=$response_Decode[0];
//print_r ($response_Decode);
//die(); //For testing
$matter_array = array();
if(!empty($response_Decode->data) && is_array($response_Decode->data)) {
foreach ($response_Decode->data as $info) {
$d = array();
$d[] = $info->display_number;
$d[] = $info->client->name;
$matter_array[] = $d;
}
}

php stdClass to array

The lazy one-liner method

You can do this in a one liner using the JSON methods if you're willing to lose a tiny bit of performance (though some have reported it being faster than iterating through the objects recursively - most likely because PHP is slow at calling functions). "But I already did this" you say. Not exactly - you used json_decode on the array, but you need to encode it with json_encode first.

Requirements

The json_encode and json_decode methods. These are automatically bundled in PHP 5.2.0 and up. If you use any older version there's also a PECL library (that said, in that case you should really update your PHP installation. Support for 5.1 stopped in 2006.)


Converting an array/stdClass -> stdClass

$stdClass = json_decode(json_encode($booking));

Converting an array/stdClass -> array

The manual specifies the second argument of json_decode as:

assoc
When TRUE, returned objects will be converted into associative arrays.

Hence the following line will convert your entire object into an array:

$array = json_decode(json_encode($booking), true);

Convert stdClass object to array in PHP

The easiest way is to JSON-encode your object and then decode it back to an array:

$array = json_decode(json_encode($object), true);

Or if you prefer, you can traverse the object manually, too:

foreach ($object as $value) 
$array[] = $value->post_id;

Using arrays VS objects for storing data

Arrays

  • There are tons of array_* functions that can work on arrays, most of which are very fast.
  • By default they passes by value (copied around)
  • Lightweight/Simple (changes only effect local variable, less to think about)
  • Often used for build once data (data that doesn't change)
  • All data is public
  • Slightly less resource intensive

Objects

  • Methods can be used to keep the data stricter. (IE. checks that a field fits a format)
  • Subclassing (reducing code duplication)
  • By default they are passed by reference
  • Changes to data can have cascading effects (__get, __set, etc)
  • Often used for data that is more mutable
  • Can protect data from outside via functions and protected/private variables
  • Function type hinting of objects is more flexible (different typehint for different classes)


Related Topics



Leave a reply



Submit