What is stdClass in PHP?
Asked Answered
W

18

1166

Please define what stdClass is.

Wield answered 31/5, 2009 at 5:49 Comment(0)
N
857

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.

Noxious answered 31/5, 2009 at 5:55 Comment(7)
maybe he used mysql_fetch_object. that creates an instance of stdlcass if im not mistaken.Sanfred
It's not quite a base class in the way Java's Object is, see my answer below.Schuss
I hope you know that object isn't the derived class of "all" objects in Python... At least, not until you are forced to derive from object in Python 3.0Obey
I think people should say that stdClass is something like JavaScript's {} construct.Interchangeable
Sir, your answer is partially incorrect because the article is incorrect. The only (and this is wrong too) thing that extending this class gives you is option to type hint it i.e. function(StdClass $a, array $params) v.s. checking if $a is object and instanceof.Prop
I agree with Earth Engine, I think of stdClass like I would a JSON object.Venuti
Y not putting a short example here, why not either referring to php.net docs?Odle
S
1175

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

Schuss answered 14/6, 2009 at 11:13 Comment(7)
It's a utility class! Btw this is the real comment!Weighting
Actually, the first sentence after the code snippet answers the question.Etan
+1. Also another major factor contributing to the difference between Java's Object class and PHP's stdClass is the dynamic properties. You are not allowed to just define dynamic properties (or variables) in a Java Object object, however, you are allowed to do so in a stdClass object in PHP.Archibald
@Miro Markaravanes: Dynamic attributes can by assigned to any class in PHP, not just stdClass.Tilford
How I wish there was a base class that I could modify. Then I could add a stdClass->methods() and my life woud be a little happier.Ironworks
@Ironworks you could now use PHP7's anonymous classes for that :)Tracietracing
@Tracietracing not quite, I wanted to modify the base class so that I could then call ->methods() on any object after that. Either way, I don't use PHP any more so it's no longer an issue.Ironworks
N
857

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.

Noxious answered 31/5, 2009 at 5:55 Comment(7)
maybe he used mysql_fetch_object. that creates an instance of stdlcass if im not mistaken.Sanfred
It's not quite a base class in the way Java's Object is, see my answer below.Schuss
I hope you know that object isn't the derived class of "all" objects in Python... At least, not until you are forced to derive from object in Python 3.0Obey
I think people should say that stdClass is something like JavaScript's {} construct.Interchangeable
Sir, your answer is partially incorrect because the article is incorrect. The only (and this is wrong too) thing that extending this class gives you is option to type hint it i.e. function(StdClass $a, array $params) v.s. checking if $a is object and instanceof.Prop
I agree with Earth Engine, I think of stdClass like I would a JSON object.Venuti
Y not putting a short example here, why not either referring to php.net docs?Odle
K
116

stdClass is a another great PHP feature. You can create a anonymous PHP class. Lets check an example.

$page=new stdClass();
$page->name='Home';
$page->status=1;

now think you have a another class that will initialize with a page object and execute base on it.

<?php
class PageShow {

    public $currentpage;

    public function __construct($pageobj)
    {
        $this->currentpage = $pageobj;
    }

    public function show()
    {
        echo $this->currentpage->name;
        $state = ($this->currentpage->status == 1) ? 'Active' : 'Inactive';
        echo 'This is ' . $state . ' page';
    }
}

Now you have to create a new PageShow object with a Page Object.

Here no need to write a new Class Template for this you can simply use stdClass to create a Class on the fly.

    $pageview=new PageShow($page);
    $pageview->show();
Katt answered 8/12, 2012 at 9:20 Comment(5)
an empty class with usefull functions that work with rows, also its a better coding standardSharanshard
It would be same as using array. In fact STDclass is generated at the time of type juggling like array to object conversion.Singlephase
Please correct a typo in your code: ($this->currentpage->name==1) should be ($this->currentpage->status==1)Evolute
"You can create a anonymous PHP class"- It's not an anonymous class. You can use instanceof, get_class, ...Elliott
This answer is particularly confusing now that PHP actually has anonymous classes, which are very different from stdClass.Fagen
L
65

Also worth noting, an stdClass object can be created from the use of json_decode() as well.

Lugger answered 11/10, 2011 at 19:11 Comment(6)
True. I frequently use json_encode and json_decode to convert array to object to array, when necessary.Dulcine
$x = json_decode(json_encode($object), True) will decode object into an array, but it's not binary safe. Essentially if it's not plaintext it might break in JSON.Mcclenaghan
@Mcclenaghan In PHP you shouldn't write True. Booleans are lower case true or false.Ose
@Ose Says who? The manual doesn't, in fact it uses all uppercase and capitalised in demonstrations, not all lowercase. It's not JavaScript.Mcclenaghan
@Mcclenaghan The manual doesn't, but PSR-2 does, so if you're following any kind of standards it should be in lower-case. Sure, if you want to write it that way it's valid but you should be following standards. The manual documentation for booleans will be extremely old, probably written before standards were formed. Let's be honest, PHP was originally written as a complete mess without any standards (see the wide range of variable/function/object naming conventions used). I've honestly never seen any PHP code where the developer used your format though.Ose
I do follow PSR-2 except for True/False/Null and putting opening braces on their own lines for classes. Other than that, I just don't care. If ever editing someone else's code, though, I follow whatever standard they're using (if any, usually none) and failing that I do, do PSR-2 the "right" way. There's plenty of god awful code out there with tons of other problems that capitalisation of three keywords is the least of my worries.Mcclenaghan
T
29

Likewise,

$myNewObj->setNewVar = 'newVal'; 

yields a stdClass object - auto casted

I found this out today by misspelling:

$GLOBASLS['myObj']->myPropertyObj->myProperty = 'myVal';

Cool!

Trimorphism answered 19/5, 2010 at 13:47 Comment(2)
But this should raise a E_NOTICECryptozoic
@Cryptozoic Only in PHP 5.3+ though right? But yeah it is bad practice for sure.Dunleavy
S
29

Using stdClass you can create a new object with its own properties. Consider the following example that represents the details of a user as an associative array:

$array_user = array();
$array_user["name"] = "smith john";
$array_user["username"] = "smith";
$array_user["id"] = "1002";
$array_user["email"] = "[email protected]";

If you want to represent the same details as the properties of an object, you can use stdClass as below:

$obj_user = new stdClass;
$obj_user->name = "smith john";
$obj_user->username = "smith";
$obj_user->id = "1002";
$obj_user->email = "[email protected]";

If you are a Joomla developer refer to [this example in the Joomla docs][1]. https://docs.joomla.org/Inserting,_Updating_and_Removing_data_using_JDatabase

Sennit answered 6/4, 2015 at 14:21 Comment(0)
M
24

The reason why we have stdClass is because in PHP there is no way to distinguish a normal array from an associate array (like in Javascript you have {} for object and [] for array to distinguish them).

So this creates a problem for empty objects. Take this for example.

PHP:

$a = [1, 2, 3]; // this is an array
$b = ['one' => 1, 'two' => 2]; // this is an associate array (aka hash)
$c = ['a' => $a, 'b' => $b]; // this is also an associate array (aka hash)

Let's assume you want to JSON encode the variable $c

echo json_encode($c);
// outputs => {'a': [1,2,3], 'b': {one: 1, two: 2}}

Now let's say you deleted all the keys from $b making it empty. Since $b is now empty (you deleted all the keys remember?), it looks like [] which can be either an array or object if you look at it.

So if you do a json_encode again, the output will be different

echo json_encode($c);
// outputs => {'a': [1,2,3], 'b': []}

This is a problem because we know b that was supposed to be an associate array but PHP (or any function like json_encode) doesn't.

So stdClass comes to rescue. Taking the same example again

$a = [1, 2, 3]; // this is an array
$b = (object) ['one' => 1, 'two' => 2]; // this makes it an stdClass
$c = ['a' => $a, 'b' => $b]; // this is also an associate array (aka hash)

So now even if you delete all keys from $b and make it empty, since it is an stdClass it won't matter and when you json_encode it you will get this:

echo json_encode($c);
// outputs => {'a': [1,2,3], 'b': {}}

This is also the reason why json_encode and json_decode by default return stdClass.

 $c = json_decode('{"a": [1,2,3], "b": {}}', true); //true to deocde as array
 // $c is now ['a' => [1,2,3], 'b' => []] in PHP
 // if you json_encode($c) again your data is now corrupted
Melodious answered 24/1, 2020 at 18:7 Comment(2)
Thanks for your details solution and i recommend your solution for deep learn 👍Scraggy
In my experience stdClass is used simply because of json_encode() and json_decode(). You can always collect the results of json_decode() as a recursive array and never need to mess with stdClass and for json_encode() you can use typecasting to (object) as shown in this answer which technically creates stdClass in process but you don't need to encode that in the actual source and do not need to mind about the actual internal implementation detail. In short, you never need to use stdClass yourself in PHP.Horror
E
23

stdClass is not an anonymous class or anonymous object

Answers here includes expressions that stdClass is an anonymous class or even anonymous object. It's not a true.

stdClass is just a regular predefined class. You can check this using instanceof operator or function get_class. Nothing special goes here. PHP uses this class when casting other values to object.

In many cases where stdClass is used by the programmers the array is better option, because of useful functions and the fact that this usecase represents the data structure not a real object.

Elliott answered 5/3, 2016 at 10:4 Comment(1)
In my experience stdClass is mostly used by accident by not understanding how json_encode() actually works in PHP. You can build the whole data you need using just (possibly recursive) array and json_encode() will emit array or object depending if you used just numerical keys or string keys in each array. If you actually need a class, it's much better to actually define a real class. The stdClass is functionally same as class stdClass {} would be.Horror
C
12

Its also worth noting that by using Casting you do not actually need to create an object as in the answer given by @Bandula. Instead you can simply cast your array to an object and the stdClass is returned. For example:

$array = array(
    'Property1'=>'hello',
    'Property2'=>'world',
    'Property3'=>'again',
);

$obj = (object) $array;
echo $obj->Property3;

Output: again

Chet answered 11/1, 2018 at 11:35 Comment(0)
S
8

stdClass objects in use

The stdClass allows you to create anonymous classes and with object casting you can also access keys of an associative array in OOP style. Just like you would access the regular object property.

Example

class Example {

  private $options;

  public function __construct(Array $setup)
  {
    // casting Array to stdClass object
    $this->options = (object) $setup;

    // access stdClass object in oop style - here transform data in OOP style using some custom method or something...
    echo $this->options->{'name'}; // ->{'key'}
    echo $this->options->surname;  // ->key
  }

}

$ob1 = new Example(["name" => "John", "surname" => "Doe"]);

will echo

John Doe

Sevier answered 23/4, 2017 at 3:52 Comment(0)
P
7

Actually I tried creating empty stdClass and compared the speed to empty class.

class emp{}

then proceeded creating 1000 stdClasses and emps... empty classes were done in around 1100 microseconds while stdClasses took over 1700 microseconds. So I guess its better to create your own dummy class for storing data if you want to use objects for that so badly (arrays are a lot faster for both writing and reading).

Pilgarlic answered 23/3, 2013 at 15:2 Comment(8)
apparently the difference is caused by the difference in name length. if you call the class "averylongclassnamefornoapparentreason", it will take a lot longer to create. so go figure.Pilgarlic
Hmmm... premature optimization. I'd rather find complex SQL queries or other network bottlenecks if I am really concerned with speed rather than spend time saving 600 microseconds. Actually, I'd rather check first if javascript is on the footer instead at the head than care if one is 600 microseconds faster than the other.Autobahn
1000 is too small for a reliable benchmark. Try a billion.Polygamy
In PHP world it's almost always better to use arrays.Bicker
^ Definitely not so. Array hell is a nightmare when working in a team on a large project.Chest
@DavieDave God ... Array?Gastrulation
I wouldn't say it's even remotely accurate to say that arrays are always better. Note even a little bit true.Sjoberg
Added to the mentioned concern that 1k iterations barely qualifies as benchmark, you'd also need to do that on real server hardware and best in real application conditions.Perpetua
A
7

php.net manual has a few solid explanation and examples contributed by users of what stdClass is, I especially like this one http://php.net/manual/en/language.oop5.basic.php#92123, https://mcmap.net/q/46800/-how-to-define-an-empty-object-in-php.

stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.

When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.

stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect.

You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.

Anthrax answered 19/6, 2016 at 14:42 Comment(0)
C
6

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

Please check the site - http://www.webmaster-source.com/2009/08/20/php-stdclass-storing-data-object-instead-array/ for more details.

Cockloft answered 14/10, 2015 at 10:2 Comment(1)
Do you have any sensible use case where PHP arrays (technically a mixture of an array and an ordered hashmap) couldn't serve the same purpose with higher performance?Horror
G
6

is a way in which the avoid stopping interpreting the script when there is some data must be put in a class , but unfortunately this class was not defined

Example :

 return $statement->fetchAll(PDO::FETCH_CLASS  , 'Tasks');

Here the data will be put in the predefined 'Tasks' . But, if we did the code as this :

 return $statement->fetchAll(PDO::FETCH_CLASS );

then the will put the results in .

simply says that : look , we have a good KIDS[Objects] Here but without Parents . So , we will send them to a infant child Care Home :)

Gotcher answered 29/9, 2017 at 12:38 Comment(0)
P
6

Please bear in mind that 2 empty stdClasses are not strictly equal. This is very important when writing mockery expectations.

php > $a = new stdClass();
php > $b = new stdClass();
php > var_dump($a === $b);
bool(false)
php > var_dump($a == $b);
bool(true)
php > var_dump($a);
object(stdClass)#1 (0) {
}
php > var_dump($b);
object(stdClass)#2 (0) {
}
php >
Pulpboard answered 13/3, 2018 at 10:48 Comment(1)
Because it is NOT same instance, ergo it cannot equal to each other. Strict comparison of classes work with instance identification. Each instance of any class has unique ID.Tacket
S
3

stClass is an empty class created by php itself , and should be used by php only, because it is not just an "empty" class , php uses stdClass to convert arrays to object style if you need to use stdClass , I recommend two better options : 1- use arrays (much faster than classes) 2- make your own empty class and use it

//example 1
$data=array('k1'=>'v1' , 'k2'=>'v2',....);

//example 2
//creating an empty class is faster than instances an stdClass
class data={}
$data=new data();
$data->k1='v1';
$data->k2='v2';

what makes someone to think about using the object style instead of array style???

Smashing answered 11/8, 2017 at 21:34 Comment(0)
B
2

You can also use object to cast arrays to an object of your choice:

Class Example
{
   public $name;
   public $age;
}

Now to create an object of type Example and to initialize it you can do either of these:

$example = new Example();
$example->name = "some name";
$example->age = 22;

OR

$example = new Example();
$example = (object) ['name' => "some name", 'age' => 22];

The second method is mostly useful for initializing objects with many properties.

Bicker answered 28/1, 2016 at 7:35 Comment(0)
R
2

stdClass in PHP is classic generic class. It has no built-in properties or methods. Basically, It's used for casting the types, creating objects with dynamic properties, etc. If you have the javascript background, You can determine as

$o = new \stdClass();

is equivalent to

const o = {};

It creates empty object, later populated by the program control flow.

Ricotta answered 7/12, 2021 at 8:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.