Ok, I've write a function that emulates the Perl's bless one. It works pretty well.

The idea comes to me when Rob suggest to parse the serialized data. I think this is better -or at least faster- than parsing all serialized data to modify object values: Just convert the object to an array, modify whatever values you want -no matter about member visibility-, and then convert the array again in an object.

Note that you should NEVER modify private and protected members outside its visibility environment... well, never UNLESS you're writting your own serialization routines indeed (that's exactly because I need to do it ;-) )

<?

function bless ( &$Instance, $Class ) {
   $serdata = serialize ( $Instance );

   /* For an array serialized data seems to meant:
        array_tag:array_count:{array_elems}

       array_tag is always 'a'
       array_count is the number of elements in the array
       array_elems are the elemens in the array

     For an object seems to meant:

object_tag:object_class_name_len:"object_class_name":object_count:{object_members}

object_tag is always 'O'
object_class_name_len is the length in chars of object_class_name string
object_class_name is a string with the name of the class
object_count is the number of object members
object_members is the object_members itself (exactly equal to array_elems)
*/


list ($array_params, $array_elems) = explode ('{', $serdata, 2);
list ($array_tag, $array_count) = explode (':', $array_params, 3 );
$serdata = "O:".strlen ($Class).":\"$Class\":$array_count:{".$array_elems;


   $Instance = unserialize ( $serdata );
   return $Instance;
}


class TestClass { private $One=1; protected $Two=2; public $Three=3;

   public function sum() {
       return $this->One+$this->Two+$this->Three;
   }
}


$Obj = new TestClass (); $Clone = (array) $Obj;

echo "As an array:<br>";
print_r ($Clone);

bless ( $Clone, TestClass );

echo "<br><br>After blessing as a TestClass instance:<br>";
print_r ($Clone);

echo "<br><br>Calling sum method: ";
echo $Clone->sum();

echo "<br>The array was blessed! miracle!!! ;-)<br>";

?>

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Reply via email to