What Is Stdclass in PHP

What is stdClass 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.

How can I loop stdClass in PHP?

You will have to iterate through _results (or maybe even try results (I do not know which framework or library you use for database communication)):

foreach($data->_results as $item) {
echo $item->username; // first result should be: jonathan@gmail.com
}

EDIT: As you have defined a public getter method results() which safely returns your private $_results variable, you can do the following:

foreach($data->results() as $item) {
echo $item->username; // first result should be: jonathan@gmail.com
}

It will work now.

How to parse stdClass object in php

You can use json_encode to convert it to a json. After which you can use json_decode with the second parameter set to true which will return an array instead of an StdObject.

If the api you're calling simply returns a json itself then you can go ahead and use json_decode directly with the second argument set to true to yield the same result.

There are other ways, but this is the simplest.

You can check out other questions, like this one or this one.

How can i read this stdClass object in php?

leagues is an object, not an array, so you need to use -> to access the property. And since it's a number rather than an identifier, you have to wrap the property name in braces.

echo $data->api->leagues->{"1"}->league_id;

How to fetch the values from stdClass in PHP?

Using json_decode(json_encode(), true) to simplify stdclass object to an associative array, because it is sometimes complicated to work with multiple mixed object and array in a single variable.

I just took a piece of the code at this part of condition and loop statement to make an example

if (($structure->parts[$i]->ifdisposition) && (strtolower($structure->parts[$i]->disposition) === 'inline')) 
{

Here is the only part I converted using json_decode(json_encode( $stdclass ),true)

It converts the stdclass object into associative arrays

    $parameters = json_decode(json_encode($structure->parts[$i]->parameters), true);
for($i =0; $i < count($parameters); $i++)
{
if(strtolower($parameters[$i]['attribute']) === 'name') {
$body_attachments[$body_number]['is_attachment'] = true;
$body_attachments[$body_number]['name'] = $parameters[$i]['name'];
}
}

End of loop

}

You can change your loop statements from object support to an array if you want to convert whole object to an associative array

you can also use this function get_object_vars( ) it also converts the object to an array but they are different with json_decode in terms with deep I have tried them both,
get_object_vars( ) only converts the parent object not the sub object values

 $parameters = (object) array('0' => 
(object) array("attribute"=> "name", "value"=>"what-is-bootstrap.png" )
);

print_r($parameters);
print_r(json_decode(json_encode($parameters), true));
print_r(get_object_vars($parameters));

and the results are

stdClass Object
(
[0] => stdClass Object
(
[attribute] => name
[value] => what-is-bootstrap.png
)
)

Array
(
[0] => Array
(
[attribute] => name
[value] => what-is-bootstrap.png
)
)

Array
(
[0] => stdClass Object
(
[attribute] => name
[value] => what-is-bootstrap.png
)
)

Read stdClass Object in php

You have to read your object.

It says that it's a standard object who contains a standard object who contains an array. So, first tell about first object than second object to end with the array's name followed by key you want to get :

$some_obj->HelloWorldResult->string[0]

For an example :

$some_obj = new stdClass();
$some_obj->HelloWorldResult = new stdClass();
$some_obj->HelloWorldResult->string = array(
0,
4546330305913,
"1395/11/20",
0
);

print_r($some_obj);

Output :

stdClass Object
(
[HelloWorldResult] => stdClass Object
(
[string] => Array
(
[0] => 0
[1] => 4546330305913
[2] => 1395/11/20
[3] => 0
)
)
)

Then to access some value :

var_dump($some_obj->HelloWorldResult->string[0]);

Output :

int(0)

PHP stdClass Object with dot

You can try using braces:

$object->GetPlayerResult->{"RegistrationResponses.Player"}

Or you can cast it to an associative array

$result = (array) $object->GetPlayerResult;
$player = $result["RegistrationResponses.Player"];

If you are parsing your website response using json_decode, note the existence of the second parameter to return as associative array:

assoc


When TRUE, returned objects will be converted into associative arrays.

Access variable of stdClass Object

Dynamic attributes with usually not allowed characters can be accessed using curly brackets like this:

$object->{"MAX(id)"}

how can I access the value of a stdclass in php

Add this to your code to get an array of all the "time" values

$times = array();
foreach ($sum_time as $value) {
$times[] = $value[0]->time;
}

Std class vs Anonymous class in PHP7+

It seems even in PHP 8 if you cast an array to object you still get stdClass:

$test = (object) [];
var_dump($test); //output: object(stdClass)#1 (0) {}

$test = new class{};
var_dump($test); //output: object(class@anonymous)#1 (0) {}

So it is safe to assume it is still the generic class in php 7 and 8.

One difference is when you want to declare some method or even the __construct method for the object:

$object = new class('value') {

private $val;

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

public function getVal(){
return $this->val;
}
};

Above code is obviously more readable regards to object orianted concepts like encapsulation.

But if you need to create an empty object I would suggest to use stdClass ( or (object)[] to type less) over anonymous class since it was intended to derive fully modelled objects.

If you want to have some public properties in the object, still (object)[] would be a more readable way to go:

$object = (object) [
"firstName" => "John",
"lastName" => "Doe"
];

$object = new class{};
$object->firstName = "John";
$object->lastName = "Doe";

If you need some methods for the object, anonymous class would be a better option.

If you want to have private properties, again anonymous class is the way to go.

If you want your object to implement some interface then definitely go with anonymous class:

interface Logger {
public function log(string $msg);
}

class Application {
private $logger;

public function getLogger(): Logger {
return $this->logger;
}

public function setLogger(Logger $logger) {
$this->logger = $logger;
}
}

$app = new Application;
$app->setLogger(new class implements Logger {
public function log(string $msg) {
echo $msg;
}
});

If you want your object to extend some class then again anonymous class is the way to go:

$object = new class extends Thread {
public function run() {
/** ... **/
}
};

$object->start();


Related Topics



Leave a reply



Submit