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.
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" => "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;
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.
Pingback: PHP stdClass: Storing Data in an Object Instead of an Array [ Webmaster-Source ]
Pingback: PHP stdClass: objetos en lugar de arrays | fprieto.es
Pingback: Compilado de enlaces útiles « droope.wordpress
Pingback: Adding a coating of civilization to PHP stdclass with the PGMObject base class : BioTeam
Pingback: SEO obligations, php must turn json data into html | njaarts
Pingback: PHP 建立物件來輸出 JSON 格式 - Tsung's Blog
Pingback: [php] structured array | PipisCrew Official Homepage