Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is stdClass in PHP?

Tags:

php

stdclass

Please define what stdClass is.

like image 257
Keira Nighly Avatar asked May 31 '09 05:05

Keira Nighly


People also ask

How do I print a stdClass object?

If you just want to print you can use var_dump() or print_r() . var_dump($obj); print_r($obj); If you want an array of all properties and their values use get_object_vars() .

What is stdClass object in codeigniter?

StdClass means an object that has no specific class. It is "just a basic object". Every object in php start out from a 'basic object' which is then extended with all the characteristics of the specific class that it is an instance of (like Model, Controller, etc).

What is object in PHP with example?

In PHP, Object is a compound data type (along with arrays). Values of more than one types can be stored together in a single variable. Object is an instance of either a built-in or user defined class. In addition to properties, class defines functionality associated with data.


2 Answers

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.

like image 21
Alex Martelli Avatar answered Sep 28 '22 04:09

Alex Martelli


stdClass is just a generic 'empty' class that's used when casting other types to objects. Despite what the other two answers say, stdClass is not the base class for objects in PHP. This can be demonstrated fairly easily:

class Foo{} $foo = new Foo(); echo ($foo instanceof stdClass)?'Y':'N'; // outputs 'N' 

I don't believe there's a concept of a base object in PHP

like image 93
Ciaran McNulty Avatar answered Sep 28 '22 04:09

Ciaran McNulty