PHP: Cannot access property started with '\0'

Some days ago I saw the following fatal error for the first time in my life:

Fatal error: Cannot access property started with '\0' in file.php

After some debugging, I found out that the source of the error was not some strange BOM or UTF-8 characters in PHP source code files. No, it was a combination of protected class properties, object-to-array casting and automatic template property mappings.

PHP changed the object-to-array casting algorithm with version 5.3.0: Protected property names get prefixed with \0*\0, private property names get prefixed with \0classname\0.

<?php
class Dummy {
    public $pub = 0;
    protected $prot = 1;
    private $priv = 2;
}
var_dump((array) new Dummy());
?>

The output of the previous code is:

array(3) {
  'pub' =>
  int(0)
  '\0*\0prot' =>
  int(1)
  '\0dummy\0priv' =>
  int(2)
}

Note that this does not happen when using get_object_vars().

This array got passed into a template engine, which set them into the template object itself:

<?php
$tpl = new stdClass();
foreach ((array) new Dummy() as $name => $val) {
    $tpl->$name = $val;
}
?>

And this leads to the aforementioned fatal error.

Written by Christian Weiske.

Comments? Please send an e-mail. Or Reply or Like.