PHP

What is stdClass? And Dynamic Properties in PHP?

Well hello there, I’m back 🙂

If you are a curious person, like me, you must have wandered in the core code of PHP frameworks like Laravel or Yii, and you must have seen this stdClass here and there. Now, let’s see what is that and how it helps us to code cleaner and more efficient.

Okay if you came from or know even just a little Java, you’ll familiar with this concept called Dynamic Properties, to create a new object in Java somehow it’ll look like this:

const x = {
    a: 'test',
    b: 'test2',
    c: 'test3'
};
Well, before PHP 5.4 object’s properties must be predefined before we can set or get it with the magic method. What a bumper! But luckily, now we can define a new object as quick and dynamic as this:
$book = new stdClass;
$book->title = "Harry Potter and the Prisoner of Azkaban";
$book->author = "J. K. Rowling";
$book->publisher = "Arthur A. Levine Books";
$book->amazon_link = "http://www.amazon.com/dp/0439136369/";

See? Sometimes all that is necessary is a property bag to throw key value pairs into. One way is to use array, but this requires quoting all keys. Another way is to use dynamic properties on an instance of StdClass. StdClass is a sparsely documented class in PHP which has no predefined properties.

You can even cast an array directly to an object in a sec:

$array = array(
    "title" => "Harry Potter and the Prisoner of Azkaban",
    "author" => "J. K. Rowling",
    "publisher" => "Arthur A. Levine Books",
    "amazon_link" => "http://www.amazon.com/dp/0439136369/"
);
 
$books = (object) $array;

To conclusion, Objects are really useful when you’re working with a large data structure, as you can have an object with nested sub-arrays in it. And StdClass (std stand for standard)is just a generic ’empty bag’ class that’s used when casting other types to objects with what ever properties you want in them. BUT despite what the others say, StdClass is not the base class for objects in PHP. Please remember that.

Next week I’ll be back with you guys to discuss about Trait 😉 See ya

Dang.NH

Reply