note 31781 added to language.types.type-juggling

From: Date: Sat, 03 May 2003 14:37:47 +0000
Subject: note 31781 added to language.types.type-juggling
Groups: php.notes 
Request: Send a blank email to php-notes+get-47440@lists.php.net to get a copy of this message
If you want to do not only typecasting between basic data types but between classes, try this function. It converts any class into another. All variables that equal name in both classes will be copied. function typecast($old_object, $new_classname) { if(class_exists($new_classname)) { $old_serialized_object = serialize($old_object); $new_serialized_object = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":' . substr($old_serialized_object, $old_serialized_object[2] + 7); return unserialize($new_serialized_object); } else return false; } Example: class A { var $secret; function A($secret) {$this->secret = $secret;} function output() {echo("Secret class A: " . $this->secret);} } class B extends A { var $secret; function output() {echo("Secret class B: " . strrev($this->secret));} } $a = new A("Paranoia"); $b = typecast($a, "B"); $a->output(); $b->output(); echo("Classname \$a: " . get_class($a) . "Classname \$b: " . get_class($b)); Output of the example code above: Secret class A: Paranoia Secret class B: aionaraP Classname $a: a Classname $b: b -- http://www.php.net/manual/en/language.types.type-juggling.php http://master.php.net/manage/user-notes.php?action=edit+31781 http://master.php.net/manage/user-notes.php?action=delete+31781 http://master.php.net/manage/user-notes.php?action=reject+31781

« previous php.notes (#47440) next »