Related
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.
I'm trying to figure out a way to call a method of a specified member (Class A) coming from an array of members in class B.
<?php
class A
{
public function do_something()
{
echo "class A did something";
}
}
class B
{
private $arr = array();
private $current_index = 0;
public function add_new_A()
{
$new_a = new A;
array_push($this->arr, (object) [
$this->current_index => $new_a
]);
$this->current_index++;
}
public function get_an_A_by_index($index)
{
return $this->arr{$index};
}
public function do_something_with_A_member_inside_array($index)
{
self::get_an_A_by_index($index)->do_someting();
}
}
$b = new B;
$b->add_new_a();
$b->add_new_a();
echo print_r($b->get_an_A_by_index(0));
echo "\n";
$b->do_something_with_A_member_inside_array(0); // returns error
// console:
// stdClass Object ( [0] => A Object ( ))
// Uncaught Error: Call to undefined method stdClass::do_something();
?>
To wrap things up, I want to know if my approach is considered bad and/or if there is something I can do to fix the error. Before you disagree with my code, take a look at my php code I'm actually working on. That's all for my question.
Now about why I want to call a method of a member A inside . For my assignment I want a program that does something seperately with the method do_something of class a. So far, the only way to do that is by storing seperate members of A.
I'm not sure if I'm approaching this wrong or not, because I'm coming from Java. So, The first thing I came up with was the approach shown above. When I do this in Java, it works fine. But php is different from Java and I'm still learning how php works since I'm new to it.
Your code isn't far off, you've just got an issue with the way you're building up the collection of A objects.
array_push($this->arr, (object) [
$this->current_index => $new_a
]);
This is creating a data structure that I'm pretty sure isn't what you expect. You'll end up with an array full of stdClass objects, each with a single A member and its own internal index:
Array
(
[0] => stdClass Object
(
[0] => A Object
(
)
)
)
You're then retrieving the stdClass object and trying to run the method on that, hence the Call to undefined method stdClass::do_something... error you're seeing.
Instead, all you need to do is this:
$this->arr[$this->current_index] = $new_a;
The rest of your code is just expecting an array of A objects, nothing nested any deeper.
I've put a full example here: https://3v4l.org/ijvQa. Your existing code had a couple of other typos, which are also fixed. You'll spot them easily enough if you turn on error reporting.
This question already has answers here:
How do I create a copy of an object in PHP?
(9 answers)
Closed 3 years ago.
Here's my code:
$words = array();
$word = "this";
$words[] = $word;
$word = "that";
$words[] = $word;
print_r($words);
class word{
private $text;
public function __construct($word){
$this->text=$word;
}
public function setWord($word){
$this->text=$word;
}
}
$class_words = array();
$word = new word("this");
$class_words[] = $word;
$word->setWord("that");
$class_words[] = $word;
print_r($class_words);
exit;
Here's the output:
Array
(
[0] => this
[1] => that
)
Array
(
[0] => word Object
(
[text:word:private] => that
)
[1] => word Object
(
[text:word:private] => that
)
)
I expected the second output to match the first in that the array should store 'this' and 'that'. It seems array_name[] = <item> makes a copy to the item when it's an array of values but not so when it's an array of objects. How do I make it copy the object to the array instead copying a reference to the object? Do I need to create a new object each time I need to add an object to the array?
If you want to copy the value of the object into the array you need to write a "getter" for the value e.g.
class word{
private $text;
public function __construct($word){
$this->text=$word;
}
public function setWord($word){
$this->text=$word;
}
public function getWord() {
return $this->text;
}
}
$class_words = array();
$word = new word("this");
$class_words[] = $word->getWord();
$word->setWord("that");
$class_words[] = $word->getWord();
print_r($class_words);
Output:
Array
(
[0] => this
[1] => that
)
Demo on 3v4l.org
$x = new X(); stores a reference to an object into $x. A subsequent $y = $x; copies the reference, not the object, so $x and $y both refer to the same object.
PHP has rather complex semantics regarding references.
Objects are always references; all your uses of $word refer to the same object and the same data structure. You need to do:
$class_words=[new word('this'),new word('that')];
Both elements of your array hold the same object. So whenever you make a change in that object, all references to that object will show that change-- they're all referring to the same object in its current state.
As mentioned previously, if you want different values, you need to either instantiate new objects, or get the property value via a getter() that returns a simple value (string, integer, boolean, etc), not the object itself.
As a side note, you can leverage the referential nature of objects to chain methods ($Obj->method1()->method2()->method3()) by having a method return a reference to the object, i.e., return $this;
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('{}');
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.