Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to clone a stdClass

I'm trying to clone a stdClass object that have an attribut which is a DateTime. But it fails. It looks like the clone is not working. Should I wrote my own __clone() method? What is wrong here?

The code:

$object = new stdClass;
$object->date = new DateTime();
var_dump($object->date);

$cloned = clone($object);
$object->date->modify('+1 day');
var_dump($cloned->date);

The output:

object DateTime (
    ->date = string (19) '2013-04-11 11:54:00'
    ->timezone_type = int 3
    ->timezone = string (13) 'Europe/Berlin'

object DateTime (
    ->date = string (19) '2013-04-12 11:54:00'
    ->timezone_type = int 3
    ->timezone = string (13) 'Europe/Berlin'
like image 435
Spir Avatar asked Apr 11 '13 09:04

Spir


1 Answers

How to "clone" a php POSCO (Plain Old StdClass Object) via cast chaining:

$cloneObj = (object) (array) $myPOSCO;
var_dump($cloneObj == $myPOSCO); // true
var_dump($cloneObj === $myPOSCO); // false
like image 99
CNSKnight Avatar answered Sep 26 '22 01:09

CNSKnight