Tag Archives: array

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

Have you ever seen a scenario where you’re accessing data as an object, such as when you’re using WordPress’s database interface or when you’re parsing XML files with SimpleXML? You have something like echo $result->name.

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->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/";

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

Continue reading →