PHP TUTORIALPHP TutorialPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP StringsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP String FunctionsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP AdvancedPHP Include and RequirePHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms FinishingPHP OOPPHP OOP IntroductionPHP OOP ClassesPHP OOP PropertiesPHP OOP ObjectsPHP OOP MethodsPHP OOP $this KeywordPHP OOP Constructors and DestructorsPHP OOP VisibilityPHP OOP InheritancePHP OOP Abstract Classes and MethodsPHP OOP InterfacesPHP OOP TraitsPHP OOP ConstantsPHP OOP StaticPHP OOP Namespaces

PHP OOP Visibility

The Definition of Visibility in OOP

Visibility of a class member (property, method or constant) is where it can be accessed. (Eg: inside the class, outside the class)

Properties, methods, and constants can be declared with visibility.

Types of Visibility

  1. Public - Can be accessed from everywhere
  2. Private - Can only be accessed within the class
  3. Protected - Can be accessed by the class declared it and by the classes that inherit the above declared class.
PHP OOP Visibility (Source:
PHP OOP Visibility (Source:

Public vs Private

Consider the following example.

class Example {
	public $name;
	private $age;
$example  = new Example;

Here we have two properties $name and $age. We have added public and private keywords to each property respectively.

What does this do? Adding public or private will change the visibility of the property.

A public property can be accessed everywhere. (Within the class and from the outside)

$example -> name; // this is valid

A private property can only be accessed by the class that defines the property.

$example -> age; // this is invalid - will thow an error

Public Visibility

A public property or method can be declared adding the public keyword in front of its declaration. (If you followed the previous chapters, you will remember that we used this.)

class Example {
	public $property = 'property'; // a public property
	public function myMethod() { // a public method
		echo 'Hello';

A method declared without a visibility keyword will be public.

class Example {
	function myMethod() {
		// a public method

Properties cannot be declared without a visibility keyword.

PHP Public Visibility

class User {
	public $name = 'Hyvor';
	public function changeName($name) {
		$this -> name = $name;
$user = new User();
// Accesing public property from outside
echo $user -> name;
echo '<br>'; // a line break

// Accessing public method from outside
$user -> changeName('Hyvor Developer');
echo $user -> name;

Run Example ››

Private Visibility

A private property or method can be declared adding the private keyword in front of its declaration.

class Example {
	private $property = 'property'; // a private property
	private function privateMethod() { // a private method
		echo $this -> property; // this is valid

A private class member can only be accessed from the methods in the class.

Assume that you have a private property $name in the User class. Any method inside the class has access to this property. But, you cannot access it from outside the class. See this example:

class User {
	private $name = 'Hyvor'; // a private property
	public function echoName() { // a private method
		echo $this -> name; // this is valid
$user = new User();
$user -> echoName(); // valid
echo $user -> name; // this will show an error

Protected Visibility

A protected property or method can be declared adding the protected keyword in front of its declaration.

class Example {
	protected $property = 'This is a protected property';
	protected function myMethod() {
		// I'm protected!

Protected properties and methods can be accessed by,

  • The class which declared the variable
  • The classes which *inherits the above declared class

* Note: You will learn more about inheriting in the next chapters. Just remember that inheriting is another interesting concept in object-oriented programming.

In these examples, we learned how to declare properties and methods with visibility. As in the first paragraph in this tutorial, class constants also have visibility. We will learn more about that in the class constants chapter.

Why Visibility is Important?

There are two reasons.

  1. To validate and restrict data
  2. To keep private things private

1. To validate and restrict data

In the real world, the quality of information is essential. In programming, the same thing exists.

We should validate the data in both setting and getting. Let's see an example.

PHP Usage of Visibility

class House {
	// color of the house
	private $color;
	// only these colors are allowed
	private $allowedColors = [
		'black', 'blue', 'red', 'green'
	public function setColor($color) {
		// Black to black (lowercase)
		$color = strtolower($color);
		if ( in_array( $color, $this -> allowedColors ) ) {
			// if $color is in the $allowedColors array 
			// we can set the color property
			$this -> color = $color;

	public function getColor() {
		if ($this -> color) {
			// if color is set
			return $this -> color;
		} else {
			// show an error message
			return 'No color is set. May be you have set a color which is not allowed';

// Example 1
$house1 = new House();
$house1 -> setColor('black');
echo $house1 -> getColor();

echo '<br>'; // a HTML line break to make it readable

$house2 = new House();
$house2 -> setColor('yellow'); // a not allowed color
echo $house2 -> getColor();

Run Example ››

In this example, we have validated the data when both setting and getting. Here is the reason:

Directly setting a property should be avoided. To set a property a public method should be used. Here we have declared the setColor($color) method for it. In this way, we can also validate the color before setting it.

Directly getting an object property is considered a bad practice. To prevent it, we have made the color property private. The correct (and recommended) way to get the color property is by calling a public method. (getColor())

Tip: When creating setter and getter functions to get a property, using the model "get + property name" and "set + property name" is effective. It will make it easier to understand by you later when you are reading your code again.
Ex: setColor() and getColor() methods in the above example.

2. To keep private things private

Consider the above House class. Think that you have a method to paint the house. This method should be public to access from outside.

Also, this method can use methods like "take the brush", "mix the paint", "start painting" to make the process easier. These methods can be declared inside the same class. But, do we need "take the brush" method to be accessed from the outside? No, we don't. So, we keep it private.

class House {
	public function paint($color) {
		// calling private methods
		$this -> takeBrush();
		$this -> mixPaint($color);
		$this -> startPainting();
	private function takeBrush {...}
	private function mixPaint($color) {...}
	private function startPainting() {...}


In this chapter, we learned about the visibility keywords (public, private, protected) and how to use them with properties and methods. Also, we learned why visibility is useful.

While going through this lesson you put two things into your TODO list: Inheritance and Class Constants. Next chapters will explain to you more about those concepts.

Facebook Twitter