#47345 [Opn]: Cloning non-object does not throw exception?

From: Date: Mon, 09 Feb 2009 09:34:09 +0000
Subject: #47345 [Opn]: Cloning non-object does not throw exception?
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-133621@lists.php.net to get a copy of this message
ID: 47345 User updated by: alt dot e-mail at gmx dot de Reported By: alt dot e-mail at gmx dot de Status: Open Bug Type: Feature/Change Request Operating System: Irrelevant PHP Version: 5.3.0beta1 New Comment: Addendum: The code for my suggestion should really be: $newColors = array(); foreach ( $colors as $color ) { try { $newColors[] = clone $color; } // do nothing, error in __clone-method or whatever catch ( MySomethingException $e ) {} // Not an object, can't be cloned, "TypeException" would be // the exception PHP throws for non-clonables. // Really do not care what that name is, just that there is one. catch ( TypeException $e ) { $newColors[] = $color; } } Previous Comments: ------------------------------------------------------------------------ [2009-02-09 09:27:01] alt dot e-mail at gmx dot de Description: ------------ Since v5.2.5, cloning a non-object results in a fatal error. In my opinion that is the wrong behaviour! It's not really a fatal error (as in DEATH, CORE-DUMP, END-OF-THE-WORLD) to clone a non-object. It's really just an exception (as in OOPS, HELP?, DO-WHAT-NOW?), that should be user-catchable. A practical example: I have an array where the values are strings or objects that can be cast to string with "__toString". If I want to create a copy of that array, I also need to clone the objects. Reproduce code: --------------- <?php class Color { // assume their values are between 0.0 and 1.0 private $r, $g, $b; public function toString() { return sprintf("#%02X%02X%02X", (int)$this->r*255, (int)$this->g*255, (int)$this->b*255); } } // somewhere in your code you create an array of colors $colors = array( "#FFF000", new Color( 0, 0, 1 ), // and many more ); // somewhere else you want to copy that array // this is the current way $newColors = array(); foreach ( $colors as $color ) { if ( is_object( $color ) { try { $newColors[] = clone $color; } // do nothing, error in __clone-method or whatever catch ( MySomethingException $e ) {} } else { $newColors[] = $color; } } // this is the way it should be $newColors = array(); foreach ( $colors as $color ) { try { $newColors[] = clone $color; } catch ( TypeException/*or something*/ $e ) { $newColors[] = $color; } } ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=47345&edit=1

« previous php.bugs (#133621) next »