Private
You can't access private property from outside a class.
class Foo
{
public $foo = 1;
protected $bar = 2;
private $baz = 3;
}
$obj = new Foo();
echo $obj->baz; // Fatal error: Cannot access private property
Use reflection to get private property.
class Foo
{
public $foo = 1;
protected $bar = 2;
private $baz = 3;
}
$obj = new Foo();
$reflector = new ReflectionObject($obj);
$property = $reflector->getProperty('baz');
$property->setAccessible(true);
echo $property->getValue($obj); // 3
Get private properties.
class Foo
{
public $foo = 1;
protected $bar = 2;
private $baz = 3;
}
$foo = new Foo();
$reflector = new <span class='keyword_code'>ReflectionObject</span>($foo);
$properties = $reflector->getProperties(ReflectionProperty::IS_PRIVATE |
ReflectionProperty::IS_PROTECTED);
array_map(function(&$x) { $x->setAccessible(true); }, $properties);
var_dump($properties);
/*
array (size=2)
0 =>
object(ReflectionProperty)[3]
public 'name' => string 'bar' (length=3)
public 'class' => string 'Foo' (length=3)
1 =>
object(ReflectionProperty)[4]
public 'name' => string 'baz' (length=3)
public 'class' => string 'Foo' (length=3)
*/
Get parent properties.
class Ford
{
private $model;
protected $foo;
public $bar;
}
class Car extends Ford
{
private $year;
}
$class = new ReflectionClass('Car');
var_dump($class->getProperties()); // First chunk of output
var_dump($class->getParentClass()->getProperties()); // Second chunk
Last update: 382 days ago