Public, private and protected in PHP

Not the most interesting post but essential for OOP PHP development:

  • public scope to make that variable/function available from anywhere, other classes and instances of the object.

  • private scope when you want your variable/function to be visible in its own class only.

  • protected scope when you want to make your variable/function visible in all classes that extend current class including the current class.

Examples

Our first class:

<?php
Class Plant {
	public $height = 'Tall';
	private $leaves = 'Long';
	protected $colour = 'Green';
}
?>

If we try accessing the properties, we get the following:

<?php
$plant = new Plant; 
echo $plant->height;
?>
// Output: 'Tall'
<?php
$plant = new Plant; 
echo $plant->leaves;
?>
// Output: Fatal error:  Cannot access private property Plant::$leaves on line
<?php
$plant = new Plant; 
echo $plant->colour;
?>
// Output: Fatal error:  Cannot access protected property Plant::$colour on line

To show how the scope setting works with extended classes, we extend our Plant class with Flower and create a function to display our variables.

<?php
Class Flower extends Plant {

	function display() {
		echo $this->height;
	}
}
?>

Using out function we get the following:

<?php
$flower = new Flower; 
echo $flower->display();
?>
// Output: 'Tall'

Changing our echo’d variable in the function display() to $this->leaves we get nothing echo’d - as the variable is private - only available to the class it is declared in.

<?php
Class Flower extends Plant {

	function display() {
		echo $this->colour;
	}
}

$flower = new Flower; 
echo $flower->display();
?>
// Output: 'Green'

Basically

public can be accessed and changed from outside the class. This cannot happen with private or protected :)

Taken from this stackoverflow question with a minor improvement.