PHP Object Examples

An object is a data type that not only allows storing data but also methods on how to handle that data. An object is a specific instance of a class that serves as template for objects.

Define a blank object

stdClass is a default object in PHP that has no properties, methods, or parent.

$obj = new stdClass();
$obj->id = 1;
$obj->name = "Product A";
print_r($obj); //Output: stdClass Object ( [id] => 1 [name] => Product A )

Convert an array to object

We have several methods to do so.

$array = array('id' => 1, 'name' => 'PHP Example');

$product1 = (object) $array;

$product2 = new stdClass();
foreach ($array as $key => $value)
    $product2->$key = $value;

$product3 = json_decode(json_encode($array), FALSE);

Convert an object to an array

$array = (array) $object;
$array = json_decode(json_encode($object), TRUE);

Merge 2 objects

Use this method if objects have no method.

$product1 = new stdClass();
$product1->id = 1;
$product1->name = 'PHP Example';
$product1->author = 'David';
$product2 = new stdClass();
$product2->id = 1;
$product2->name = 'jQuery Example';
$products = (object) array_merge((array) $product1, (array) $product2);
//output: stdClass Object ( [id] => 1 [name] => jQuery Example [author] => David )

Data from $product2 overrides the one in the same property of $product1.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.