What is stdClass in PHP? - php

Please define what stdClass is.

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

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.

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();

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

Using stdClass you can create a new object with it's 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"] = "smith#nomail.com";
If you need 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 = "smith#nomail.com";
If you are a Joomla developer refer this example in the Joomla docs for further understanding.

Likewise,
$myNewObj->setNewVar = 'newVal';
yields a stdClass object - auto casted
I found this out today by misspelling:
$GLOBASLS['myObj']->myPropertyObj->myProperty = 'myVal';
Cool!

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.

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

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

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

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).

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://stackoverflow.com/a/1434375/2352773.
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.

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 >

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.

stdclass is a way in which the php 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 php will put the results in stdclass .
simply php says that : look , we have a good KIDS[Objects] Here but without Parents . So , we will send them to a infant child Care Home stdclass :)

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???

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.

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.

Related

What does the generic "stdClass" stand for in PHP? [duplicate]

Please define what stdClass is.
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
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.
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();
Also worth noting, an stdClass object can be created from the use of json_decode() as well.
Using stdClass you can create a new object with it's 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"] = "smith#nomail.com";
If you need 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 = "smith#nomail.com";
If you are a Joomla developer refer this example in the Joomla docs for further understanding.
Likewise,
$myNewObj->setNewVar = 'newVal';
yields a stdClass object - auto casted
I found this out today by misspelling:
$GLOBASLS['myObj']->myPropertyObj->myProperty = 'myVal';
Cool!
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.
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
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
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
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).
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://stackoverflow.com/a/1434375/2352773.
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.
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 >
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.
stdclass is a way in which the php 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 php will put the results in stdclass .
simply php says that : look , we have a good KIDS[Objects] Here but without Parents . So , we will send them to a infant child Care Home stdclass :)
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???
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.
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.

Why stdClass is coming instead of our custom object name?

Here My class name is User, When I print my class properties I'm getting my objective name properly. After that, I encoded the data with json_encode(). and then I decoding with json_decode(). I'm getting stdClass objective why?
<?php
class User
{
public $name;
public $age;
public $salary;
}
$user = new User();
$user->name = 'Siddhu';
$user->age = 24;
$user->salary = 7000.80;
print_r($user);
//Output: User Object ( [name] => Siddhu [age] => 24 [salary] => 7000.8 )
print_r(json_encode($user));
//Output: {"name":"Siddhu","age":24,"salary":7000.8}
$d = json_encode($user);
$s = json_decode($d);
print_r($s);
//Output: stdClass Object ( [name] => Siddhu [age] => 24 [salary] => 7000.8 )
If you noticed stdClass is coming, How can I change to user
There is no direct way you can get data in class object either you need to used custom method to decode else you can use serialize() && unserialize() function to get data in the class object when you decode;
$serialized_user_object = serialize($user);
$deserialized_user_object = unserialize($serialized_user_object);
In json_decode you can pass true in second argument if you want data as array.
like this.
var_dump(json_decode($json, true));
to know more about json_decode see here.
The reason this happens can be demonstrated quite easily...
class foo{
public $bar = 'bar';
}
$json = json_encode(new foo);
echo $json."\n\n";
print_r(json_decode($json));
Output
{"bar":"bar"}
stdClass Object
(
[bar] => bar
)
Sandbox
As you can see the output {"bar":"bar"} contains no information about what if any class this was, it could have been ['bar'=>'bar'] and the JSON would be the same... Then when decoding it, you don't have json_decode set to return as an array (second argument set to true), which is fine as that's not really what you want, but when it's set that way you get stdClass objects instead of an associative array for items with non-numeric keys. In short there is no way to recover the class "foo" from the json {"bar":"bar"} as that information does't exist (you can make it exist, but that's another tale for another day).
Using serialize we get something very different.
class foo{
public $bar = 'bar';
}
$json = serialize(new foo);
echo $json."\n\n";
print_r(unserialize($json));
Output
O:3:"foo":1:{s:3:"bar";s:3:"bar";}
foo Object
(
[bar] => bar
)
Sandbox
This O:3:foo means an Object with a class name 3 in length named "foo". So it preserves that information for PHP to use when "decoding" the data.
The whole thing reads like this:
Object (3) "foo" with 1 property named (s)tring (3) "bar" with a value of (s)tring (3) "bar", or something like that.
Make sense.
AS a note PHP's serialize is less portable then JSON, as it only works in PHP, It's also much harder to manually edit then JSON, but if you really want to encode a class than that is the easiest way to do it. That said you can also "repopulate" the class from JSON data, but that can also be hard to maintain.

Transparent array and object casting

When you get some database record using PHP extensions of 3rd party libraries you know that some of them return an array and some other return object, during web development I have to cast such object to array and vice versa, or at least remember that foo is array and boo is object and using proper syntax to access the record attributes. This is annoying and I think perhaps there was a syntax sugar that make it a litter easier, isn't it?
I want access to attributes of a recode regardless of it structure. because we know to following structure have same syntactical power.
$foo = ['a'=>'b','x'=>'y'];
$foo = new stdClass();
$foo->a='b';
$foo->x='y';
In javscript: foo={a:'b',x:'y'}; and then x= foo['a']; or x= foo.a; if this is possible in JS why not in PHP?
You can use (object)$array_name to typecast (change type of variable to object) and vise versa (array)$obj_name
//Array To Object Example
$person = array (
   'firstname' => 'Richard',
   'lastname' => 'Castera'
);
 
$p = (object) $person;
echo $p->firstname; // Will print 'Richard'
//Object to Array Example
$array = (array) $object;
There is no easy way to do this I can write you a code that uses PHP ArrayObject Class and converts every object / array to PHP ArrayObject (http://php.net/manual/en/class.arrayobject.php) but this will be more complex then typecasting

Dynamically discover/process PHP object

Is it possible to dynamically discover the properties of a PHP object? I have an object I want to strip and return it as a fully filled stdClass object, therefore I need to get rid of some sublevel - internal - objecttypes used in the input.
My guess is I need it to be recursive, since properties of objects in the source-object can contain objects, and so on.
Any suggestions, I'm kinda stuck? I've tried fiddling with the reflection-class, get_object_vars and casting the object to an array. All without any success to be honest..
tested and this seems to work:
<?php
class myobj {private $privatevar = 'private'; public $hello = 'hellooo';}
$obj = (object)array('one' => 1, 'two' => (object)array('sub' => (object)(array('three' => 3, 'obj' => new myobj))));
var_dump($obj);
echo "\n", json_encode($obj), "\n";
$recursive_public_vars = json_decode(json_encode($obj));
var_dump($recursive_public_vars);
You can walk through an object's (public) properties using foreach:
foreach ($object as $property => $value)
... // do stuff
if you encounter another object in there (if (is_object($value))), you would have to repeat the same thing. Ideally, this would happen in a recursive function.

How to define an empty object in PHP

with a new array I do this:
$aVal = array();
$aVal[key1][var1] = "something";
$aVal[key1][var2] = "something else";
Is there a similar syntax for an object
(object)$oVal = "";
$oVal->key1->var1 = "something";
$oVal->key1->var2 = "something else";
$x = new stdClass();
A comment in the manual sums it up best:
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.
The standard way to create an "empty" object is:
$oVal = new stdClass();
But I personally prefer to use:
$oVal = (object)[];
It's shorter and I personally consider it clearer because stdClass could be misleading to novice programmers (i.e. "Hey, I want an object, not a class!"...).
(object)[] is equivalent to new stdClass().
See the PHP manual (here):
stdClass: Created by typecasting to object.
and here:
If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.
and here (starting with PHP 7.3.0, var_export() exports an object casting an array with (object)):
Now exports stdClass objects as an array cast to an object ((object) array( ... )), rather than using the nonexistent method stdClass::__setState(). The practical effect is that now stdClass is exportable, and the resulting code will even work on earlier versions of PHP.
However remember that empty($oVal) returns false, as #PaulP said:
Objects with no properties are no longer considered empty.
Regarding your example, if you write:
$oVal = new stdClass();
$oVal->key1->var1 = "something"; // this creates a warning with PHP < 8
// and a fatal error with PHP >=8
$oVal->key1->var2 = "something else";
PHP < 8 creates the following Warning, implicitly creating the property key1 (an object itself)
Warning: Creating default object from empty value
PHP >= 8 creates the following Error:
Fatal error: Uncaught Error: Undefined constant "key1"
In my opinion your best option is:
$oVal = (object)[
'key1' => (object)[
'var1' => "something",
'var2' => "something else",
],
];
I want to point out that in PHP there is no such thing like empty object in sense:
$obj = new stdClass();
var_dump(empty($obj)); // bool(false)
but of course $obj will be empty.
On other hand empty array mean empty in both cases
$arr = array();
var_dump(empty($arr));
Quote from changelog function empty
Objects with no properties are no longer considered empty.
Short answer
$myObj = new stdClass();
// OR
$myObj = (object) [
"foo" => "Foo value",
"bar" => "Bar value"
];
Long answer
I love how easy is to create objects of anonymous type in JavaScript:
//JavaScript
var myObj = {
foo: "Foo value",
bar: "Bar value"
};
console.log(myObj.foo); //Output: Foo value
So I always try to write this kind of objects in PHP like javascript does:
//PHP >= 5.4
$myObj = (object) [
"foo" => "Foo value",
"bar" => "Bar value"
];
//PHP < 5.4
$myObj = (object) array(
"foo" => "Foo value",
"bar" => "Bar value"
);
echo $myObj->foo; //Output: Foo value
But as this is basically an array you can't do things like assign anonymous functions to a property like js does:
//JavaScript
var myObj = {
foo: "Foo value",
bar: function(greeting) {
return greeting + " bar";
}
};
console.log(myObj.bar("Hello")); //Output: Hello bar
//PHP >= 5.4
$myObj = (object) [
"foo" => "Foo value",
"bar" => function($greeting) {
return $greeting . " bar";
}
];
var_dump($myObj->bar("Hello")); //Throw 'undefined function' error
var_dump($myObj->bar); //Output: "object(Closure)"
Well, you can do it, but IMO isn't practical / clean:
$barFunc = $myObj->bar;
echo $barFunc("Hello"); //Output: Hello bar
Also, using this synthax you can find some funny surprises, but works fine for most cases.
php.net said it is best:
$new_empty_object = new stdClass();
In addition to zombat's answer if you keep forgetting stdClass
function object(){
return new stdClass();
}
Now you can do:
$str='';
$array=array();
$object=object();
You can use new stdClass() (which is recommended):
$obj_a = new stdClass();
$obj_a->name = "John";
print_r($obj_a);
// outputs:
// stdClass Object ( [name] => John )
Or you can convert an empty array to an object which produces a new empty instance of the stdClass built-in class:
$obj_b = (object) [];
$obj_b->name = "John";
print_r($obj_b);
// outputs:
// stdClass Object ( [name] => John )
Or you can convert the null value to an object which produces a new empty instance of the stdClass built-in class:
$obj_c = (object) null;
$obj_c->name = "John";
print($obj_c);
// outputs:
// stdClass Object ( [name] => John )
Use a generic object and map key value pairs to it.
$oVal = new stdClass();
$oVal->key = $value
Or cast an array into an object
$aVal = array( 'key'=>'value' );
$oVal = (object) $aVal;
to access data in a stdClass in similar fashion you do
with an asociative array just use the {$var} syntax.
$myObj = new stdClass;
$myObj->Prop1 = "Something";
$myObj->Prop2 = "Something else";
// then to acces it directly
echo $myObj->{'Prop1'};
echo $myObj->{'Prop2'};
// or what you may want
echo $myObj->{$myStringVar};
You can try this way also.
<?php
$obj = json_decode("{}");
var_dump($obj);
?>
Output:
object(stdClass)#1 (0) { }
If you want to create object (like in javascript) with dynamic properties, without receiving a warning of undefined property.
class stdClass {
public function __construct(array $arguments = array()) {
if (!empty($arguments)) {
foreach ($arguments as $property => $argument) {
if(is_numeric($property)):
$this->{$argument} = null;
else:
$this->{$property} = $argument;
endif;
}
}
}
public function __call($method, $arguments) {
$arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).
if (isset($this->{$method}) && is_callable($this->{$method})) {
return call_user_func_array($this->{$method}, $arguments);
} else {
throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
}
}
public function __get($name){
if(property_exists($this, $name)):
return $this->{$name};
else:
return $this->{$name} = null;
endif;
}
public function __set($name, $value) {
$this->{$name} = $value;
}
}
$obj1 = new stdClass(['property1','property2'=>'value']); //assign default property
echo $obj1->property1;//null
echo $obj1->property2;//value
$obj2 = new stdClass();//without properties set
echo $obj2->property1;//null
As others have pointed out, you can use stdClass. However based on the question, it seems like what you really want is to be able to add properties to an object on the fly. You don't need to use stdClass for that, although you can. Really you can use any class. Just create an object instance of any class and start setting properties. I like to create my own class whose name is simply o with some basic extended functionality that I like to use in these cases and is nice for extending from other classes. Basically it is my own base object class. I also like to have a function simply named o(). Like so:
class o {
// some custom shared magic, constructor, properties, or methods here
}
function o() {
return new o();
}
If you don't like to have your own base object type, you can simply have o() return a new stdClass. One advantage is that o is easier to remember than stdClass and is shorter, regardless of if you use it as a class name, function name, or both. Even if you don't have any code inside your o class, it is still easier to memorize than the awkwardly capitalized and named stdClass (which may invoke the idea of a 'sexually transmitted disease class'). If you do customize the o class, you might find a use for the o() function instead of the constructor syntax. It is a normal function that returns a value, which is less limited than a constructor. For example, a function name can be passed as a string to a function that accepts a callable parameter. A function also supports chaining. So you can do something like:
$result= o($internal_value)->some_operation_or_conversion_on_this_value();
This is a great start for a base "language" to build other language layers upon with the top layer being written in full internal DSLs. This is similar to the lisp style of development, and PHP supports it way better than most people realize. I realize this is a bit of a tangent for the question, but the question touches on what I think is the base for fully utilizing the power of PHP.
EDIT/UPDATE:
I no longer recommend any of this. It makes it hard for static analysis tools and IDEs and custom AST based tools to understand, validate, help you lookup or write your code. Generally magic is bad except in some cases if you are able to get your tools to understand the magic and if it you do it in a standard enough way that even standard community tools will understand it or if your tools are so advanced and full featured that you only use your own tools. Also, I think they are deprecating the ability to add properties to random objects in an upcoming version of PHP, I think it will only work with certain ones, but I don't recommend using that feature anyways.
If you don't want to do this:
$myObj = new stdClass();
$myObj->key_1 = 'Hello';
$myObj->key_2 = 'Dolly';
You can use one of the following:
PHP >=5.4
$myObj = (object) [
'key_1' => 'Hello',
'key_3' => 'Dolly',
];
PHP <5.4
$myObj = (object) array(
'key_1' => 'Hello',
'key_3' => 'Dolly',
);
Here an example with the iteration:
<?php
$colors = (object)[];
$colors->red = "#F00";
$colors->slateblue = "#6A5ACD";
$colors->orange = "#FFA500";
foreach ($colors as $key => $value) : ?>
<p style="background-color:<?= $value ?>">
<?= $key ?> -> <?= $value ?>
</p>
<?php endforeach; ?>
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.
<?php
// ways of creating stdClass instances
$x = new stdClass;
$y = (object) null; // same as above
$z = (object) 'a'; // creates property 'scalar' = 'a'
$a = (object) array('property1' => 1, 'property2' => 'b');
?>
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.
<?php
// CTest does not derive from stdClass
class CTest {
public $property1;
}
$t = new CTest;
var_dump($t instanceof stdClass); // false
var_dump(is_subclass_of($t, 'stdClass')); // false
echo get_class($t) . "\n"; // 'CTest'
echo get_parent_class($t) . "\n"; // false (no parent)
?>
You cannot define a class named 'stdClass' in your code. That name is already used by the system. You can define a class named 'Object'.
You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.
(tested on PHP 5.2.8)
You have this bad but usefull technic:
$var = json_decode(json_encode([]), FALSE);
You can also get an empty object by parsing JSON:
$blankObject= json_decode('{}');

Categories