What is stdClass in PHP?

There has some points about of stdClass in PHP.

1.stdClass is php’s generic empty class
2.It is useful for anonymous objects, dynamic properties, etc.
3.an stdClass object can be created from the use of json_decode() as well.

PHP stdClass: Storing Data in an Object Instead of an Array

Have you ever wondered how that was done? Using PHP’s stdClass feature you can create an object, and assign data to it, without having to formally define a class.

Suppose you wanted to quickly create a new object to hold some data about a book. You would do something like this:
$book = new stdClass;
$book-&gt;title = “Harry Potter and the Prisoner of Azkaban”;
$book-&gt;author = “J. K. Rowling”;
$book-&gt;publisher = “Arthur A. Levine Books”;
$book-&gt;amazon_link = “http://www.amazon.com/dp/0439136369/”

You can then access the data by calling $book-&gt;title and so on.

Or what if you wanted to take an array and turn it into an object? You can do that by casting the variable.

$array = array(
“title” =&gt; “Harry Potter and the Prisoner of Azkaban”,
“author” =&gt; “J. K. Rowling”,
“publisher” =&gt; “Arthur A. Levine Books”,
“amazon_link” =&gt; “http://www.amazon.com/dp/0439136369/”

$books = (object) $array;

This should produce the same result as the previous code snippet. You could also go the other direction, casting an object into an array by using $array = (array) $object.

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, as SimpleXML tends to return. You get most of the data as properties of the result set object, and the posts in an RSS feed are assigned to array entries, which then have further objects inside them.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s