Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is PHP private variables got public when extended class

Tags:

php

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();
print_r($retHola);

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.

like image 862
Oscar Gallardo Avatar asked Feb 06 '23 21:02

Oscar Gallardo


2 Answers

print_r is a special magic function that will show the class including private and protected properties. It's a debugging utility function. Quoting from the manual:

print_r(), var_dump() and var_export() will also show protected and private properties of objects with PHP 5. Static class members will not be shown.

In PHP, private properties are inherited in derived classes, but they are not accessible.

like image 177
Ryan Avatar answered Feb 10 '23 09:02

Ryan


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.

like image 30
Barmar Avatar answered Feb 10 '23 11:02

Barmar