Dynamically discover/process PHP object - php

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.

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.

Session variable in PHP containing object is changed when original object is changed

In some third party code, that I am not allowed to change, something peculiar is happening.
They write a variable (an array containing objects) to the session (without serialising it) and then iterate using a foreach on the original variable (without using references). Whenever they change a value, the corresponding value in the session is also changed. I was able to create a smaller example that has the same behaviour:
$test = array((object)array("categories" => "test"));
$_SESSION['woot'] = $test;
print_r($_SESSION['woot']);
foreach ($test as $a) {
if (!is_array($a->categories)) $a->categories = array();
}
print_r($_SESSION['woot']);
This is the result:
Array
(
[0] => stdClass Object
(
[categories] => test
)
)
Array
(
[0] => stdClass Object
(
[categories] => Array
(
)
)
)
I already noticed that, when I serialize and unserialize the object array, the problem does not occur.
Does anyone have an idea about what's happening here? Is it the code? Is it an incorrect server setting? I'd like to know a little more before I contact the devs of the code.
Additional information:
I am using PHP Version 5.3.14
Register globals is switched off
Regards,
Joost.
A variable holding an object only holds a reference to that object. Assigning an object (an object reference) from one variable to another does not make a copy of the object, there's still only one object. If you modify that object, all variables holding a reference to that object will see the change, because there's only one object instance.
If you want to make a copy of an object, you need to explicitly clone it.
In PHP objects are passed by reference and PHP uses copy-on-write.
$test = array((object)array("categories" => "test"));
// it is still the same array
$_SESSION['woot'] = $test;
foreach ($test as $a) {
// You change something in an object, which is passed by reference
if (!is_array($a->categories)) $a->categories = array();
}
Serialization and deserialization creates new objects
$test = array((object)array("categories" => "test"));
// new array with new objects
$test = unserialize(serialize($test));

PHP JSON get the name of an object

<?
stdClass Object
(
[image_header] => Array
(
[0] => stdClass Object
(
[img] => /headers/header.jpg
)
)
)
?>
Object name image_header is variable, so it can be any string. Can I access this string without knowing what it is?
#Jon his answer was satisfying for me.
For others who want to use variable objectnames this way:
To acces this object with the variablename I had to use curly brackets:
$key = key(get_object_vars($_json));
$_json->{$key}[0]->img;
You can do it conveniently with get_object_vars:
$propertyName = key(get_object_vars($object));
If you don't know what the name of the property is, you can use PHP's Reflection classes, or more simply use get_object_vars().
get_object_vars() is probably what you're looking for here - it "Returns an associative array of defined object accessible non-static properties for the specified object in scope. If a property has not been assigned a value, it will be returned with a NULL value." So, you get the property names and their values returned in an associative array.
Alternatively, you could use some of PHP's reflection magic, although it might be a bit overkill here, depending on your end goal. The reflection classes are very powerful, and may be worth using if you have more complex requirements for what you're trying to achieve. As an example:
// let's say $obj is the object you provided in your question
// Instantiate the reflection object
$reflector = new ReflectionClass($obj);
// Get properties of $obj, returned as an array of ReflectionProperty objects
$properties = $reflector->getProperties();
foreach ( $properties as $property ) {
echo $property->getName(); // In your example, this would echo 'image_header'
}
There are a couple of possibilities. If you're using json_decode() you can pass true in as the second parameter to parse the data as an associative array.
$data = json_decode($myJson, true);
print_r( $data['image_header'] );
You can also access an object property from a variable like this.
$myProperty = 'image_header';
print_r( $data->$myProperty );
If by "you don't know what it is" you mean you don't know the key at all you can use my first example and use array_values() to get the values by index.
$values = array_values($data);
// image_header
print_r( $values[0] );

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

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

Categories