|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2009-02-09 09:27 UTC] 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; }
}
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Dec 03 20:00:01 2025 UTC |
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; } }