PHP Tips and Tricks

Convert a PHP Object to an array

When casting a PHP Object to an array, normally you lose the protected/private data members. This won't always work for your needs. Here is the code to convert a object to an array, keeping the protected and private data members in the new array.

function objectToArray($object) {
    $dump = '$dump = '.var_export($object, true);
    $dump = preg_replace('/object\([^\)]+\)#[0-9]+ /', 'array', $dump);
    $dump = preg_replace('/[a-zA-Z_]+::__set_state/', '', $dump);
    $dump = str_replace(':protected', '', $dump);
    $dump = str_replace(':private', '', $dump);
    $dump .= ';';
    eval($dump);
    return $dump;
}
        

Converting php short tags with sed

At times I come across old php code that still uses short tags. I use this handy one liner to convert them:

sed -i'' -e 's/<?=\([^?>]*\)?>/<?php echo \1; ?>/g' -e 's/<? /<?php /g' *.php