PHP Classes and NULL characters

Today I ran into an interesting problem with PHP. It boils down to PHP’s handling of protected and private members of classes. Basically, when serializing or typecasting, NULL characters precede the variable names. For instance:

class TestClass {

    private     $var1;
    protected   $var2;
    public      $var3;
}

$instance = new TestClass();

//print_r() to a string and escape special characters
$str1 = addslashes(print_r((array) $instance, true));
echo $str1;

Outputs:

Array
(
    [\\0TestClass\\0var1] => 
    [\\0*\\0var2] => 
    [var3] => 
)

As you can see, this is probably not what you expected. Protected variable names are preceded by a NULL character, *, and another NULL character. Private variables are preceded by a NULL character, the class name, and another NULL character. This is probably one of the most idiotic things I have ever seen PHP do.

  • Violates access restrictions to class members, although serialization has that inherent flaw as well
  • Why in the world would anyone want NULL characters in the array keys?
  • Inserting serialized strings into a DB is a pain

After pondering possible reasons for this, I have come up with nothing that makes that much sense. It makes typecasting to an array pretty worthless since all members must be public.