PHP Object Examples

An object is a data type that not only allows storing data but also method on, how to handle that data. An object is a specific instance of a class which serve as templates for objects.

Define a blank object

stdClass is a default object in PHP which 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 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.

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.