A couple of years ago when I was studying PHP 5 OOP, I did a couple of scripts to test the different aspects of PHP’s particular object implementation. Since I’m currently migrating a whole bunch of PHP 4 scripts to PHP 5, I’ve decided to consult my notes, which I’m presenting here, plus some explanations for extra clarity.

This are my notes on Attributes and Method visibility within Objects.

First we create a simple class with an attribute (variable) of each type of visibility:


class MyClass {
	public $public = 'public';
	protected $protected = 'protected';
	private $private = 'private';
	function printHello() {
		echo $this->public; echo ', ';
		echo $this->protected; echo ', ';
		echo $this->private;
	}
}

Accessing Attributes Directly


$obj = new MyClass;
echo $obj->public; //Works
//echo $obj->protected; //Fatal Error
//echo $obj->private; //Fatal Error

$obj->printHello(); //Prints Everything.

Access Conclusions

Public attributes can be accessed directly.

Protected and Private can not.

Accesibility in Child classes


class MyClass2 extends MyClass {
	function testPublic() {
		echo $this->public; //Prints "Public".
	}
	function testProtected() {
		echo $this->protected; //Prints "Protected".
	}
	function testPrivate() {
		echo $this->private; //Prints nothing.
	}
}
$obj2 = new MyClass2;
$obj2->printHello(); //Prints everything.
$obj2->testProtected(); //Prints "Protected".
$obj2->testPrivate(); //Prints nothing.

Conclusions

Public and Protected attributes can be accessed in child objects.

Private can not.

Redeclaring (or Overriding ) attributes in Child classes


class myClass3 extends myClass {
	public $public = 'new public value';
	protected $protected = 'new protected value';
	private $private = 'new private value';
}
$obj3 = new MyClass3;
$obj3->printHello(); //Prints "new public value, new protected value, private"

Conclusions

Public and Protected attributes can be redeclared in child objects.

Private can not. If redeclared, the redeclaration will not take effect.

Final Conclusions

Note: The same holds true for object methods.

Encapsulation is the reason behind the separation of methods and attributes by levels of visibility. When refactoring an object, Private methods and attributes can be modified freely since they are only accesible within the object and never directly in the scripts or by inheritance in another objects. Protected makes things a little more complex since even though they can not be accessed directly, they can be accessed, redeclared or overriden by child classes. Lots of care needs to be taken when refactoring Public methods or attributes.