Tag Archives: properties

Accessing private properties in PHP 5 objects

With the introduction of PHP 5 comes the ability to define class properties and methods in a more traditional style to C++ and other popular OOP languages. The three major distinctions are Public (designated by default), Private and Protected.


class TestClass {

 	public $VarA = 'I am public!';
 	private $VarB = 'I am private!';
 	protected $VarC = 'I am protected!';


$NewInstance = new TestClass;

print($NewInstance->VarA); /* No problem */
// print($NewInstance->VarB); /* Error */
// print($NewInstance->VarC); /* Error */

$NewInstance is initiated as an instance of TestClass. $VarA can be easily accessed using $NewInstance->VarA, however trying to access VarB and VarC in the same manner will generate an error as they are designated inaccessable outside the current class (or sublcasses in the case of VarC). It is sometimes necessary to access Private and Protected object variables and this can be achieved very easily using just one line of code:

 	var_dump( (array) $NewInstance );

This will generate a dump containing a list of all object properties, including private and protected variables. Each will have an assigned key that follows the pattern of:

[“?class name?private property name”] = PRIVATE PROPERTIES
[“?*?protected property name”] = PROTECTED PROPERTIES

By type-casting to an array, the object properties are forcibly revealed in the same way you can reduce an object to a string using serialize().