Old Versions

Book

Contact

Email Me

2007.04.04 - Type Casting in PHP
2007.04.04 - Wifi DS Belkin Router Help
2006.03.29 - Test 024: Flash 8 - File Uploads
2006.02.22 - The Old Issues!
2006.02.22 - The Flash Experiments and Stuff
2006.02.22 - The Tests and Stuff
2006.02.22 - Old Stuff
2006.01.23 - Dear Jean-Cristophe
2006.01.22 - Anti Spam on Blogs

2007.04.04 - Type Casting in PHP

OK so type casting isn't supported in PHP ... HOORAY! So I went to the php help pages and made a wee type casting utility based on the kludge that some other developer came up with - the cool thing about mine is it will let you convert normal variables into objects too!

Here is a wee sample: -

class ClassA
{
var $a;
var $b;
var $c;
var $d;

function ClassA()
{
}

function ToString()
{
echo "I contain " . $this->a . ", " . $this->b . ", " . $this->c . " and " . $this->d . ".";
}
}

class Cast0r
{
function Cast($value, $asObject)
{
$value = (object) $value;
$value_array = explode(":", serialize($value));
$object_array = explode(":", serialize($asObject));

$value_array[1] = $object_array[1];
$value_array[2] = $object_array[2];

$value_object = unserialize(implode(":", $value_array));

return $value_object;
}
}

$my_arr = array(
"a" => "A",
"b" => "B",
"c" => "C",
"d" => "D"
);

$my_a = Cast0r::Cast($my_arr, new ClassA());
$my_a->ToString();

PHP Article where I found the original code - do a search on "kludge" and you'll get to the article

Comments

No comments made for this post.

Speak Your Brain

Name *
Email *
URL
Secret No.
Confirm No. *
Your Comment Here *