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.
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()
andvar_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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With