Oscar David Oscar David - 4 months ago 7x
PHP Question

Why is PHP private variables got public when extended class

I created the follow class
PHP ver 5.5

abstract class Model
var $id;

private $cName;
private $tName;

public function __construct($id = 0)
$this->cName = 'Im cName';
$this->tName = 'Im tName';

then an extended class

class claseExtend extends Model
var $id;

public function hola()
$this->id = 1;
return (array) $this);

if I Execute this:

$obj = new claseExtend() ;
$retHola =$obj->hola();

I was Expecting to get: array(id => 1)

But the output is: array( \u0000Model\u0000cName: => 'Im cName',
\u0000Model\u0000tName => 'Im tName')

What Am I doing wrong, or why is this happening if the attributes are private?

┬┐Why the array cast includes the private properties?

thanks for your help.


When you cast an object to an array, private and protected properties are included in the result. The documentation says:

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.

Those null bytes are shown in your results as \u0000.