EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Protected in PHP

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » PHP Tutorial » Protected in PHP

protected in php

Introduction to Protected in PHP

Keywords are basically a set of special words that are reserved in every programming language for a specific purpose. They can be either commands or parameters and they cannot be used for common use like variable names. Protected in PHP are predefined in all languages including PHP and also called reserved names.

There are 5 kinds of access modifiers in PHP:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  • Public
  • Private
  • Protected
  • Abstract
  • Final

We shall concentrate on only protected access modifiers in this article. Apart from variables, protected keywords are also used for declaring methods/functions and properties as protected. Unless specified explicitly, all the variables and methods will be public by default. The protected variable decreases the visibility of the respective variable or method because its access is restricted to the class in which it is declared. Protected access modifiers cannot be applied for classes.

However, they can be called by a subclass which is inherited from its parent class. Hence one can declare the required method or a variable as protected by prefixing it with a “protected” keyword.

Syntax:

<?php
//declaration of protected variable
protected $<variable_name> = value;
//declaration of protected property
protected $proc = 'protected property';
//declaration of protected function
protected function function_name(){
//PHP code goes here
}
?>

Here we can see that using protected keyword we are declaring both variable and function names.

Working of protected modifiers in PHP: Like the private access modifier, we can also use protected for restricting the usage and accessing of class functions and variables outside of the class. But one exception of protected from private variables is that they can be accessed through inheritance from its parent class in a subclass.

Examples of a Protected Variable and Method

Let us understand the usage and working of protected modifier in detail by taking a simple example below:

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (6,063 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

Example #1

Code:

<?php
// Declaration of Main class
class Math {
protected $a = 30;
protected $b = 10;
// Declaration of division function
function division()
{
echo $div=$this->a/$this->b;
echo "\n";
}
protected function multiply()
{
echo $mul=$this->a*$this->b;
echo "\n";
}
}
// Declaration of child class addn inherited from above class
class addn extends Math {
// Declaration of addition function
function addition()
{
echo $division=$this->a+$this->b;
}
}
$obj= new addn;
$obj->division();
$obj->addition();
$obj->multiply();
?>

Output:

protected in php

After commenting on line 29 which is trying to call the protected method

protected in php

In the above example, we are showcasing the different mathematical operations like addition, division, and multiplication. First, we are declaring division() function without any access modifier. Hence by default, it is public and the division value we are performing on both variables a and b are displayed in the output when we call the function by creating its object. But when we try to call the protected function multiply() we get the error inline 34 saying that protected method cannot be called.

Whereas we can call and get the value of a protected method via inheritance as shown. Here the child class and is inherited from parent class Math and hence we are able to call the protected variables a and b without any error.

Example #2

Code:

<?php
class Animal {
// Declaration of protected variable $animal
protected $animal = array("Dog", "Cat", "Cow");
// Declaration of protected function for Animal description
protected function getDescription($animal) {
if($animal == "Dog") {
echo "Dogs are the most loyal animals";
}
else if($animal == "Cat") {
echo "Cats are very smart";
}
else if($animal == "Cow") {
echo "Cows are worshipped in India";
}
}
}
// Declaration of sub class of above Animal class
class Dog extends Animal {
protected $animal = "Dog";
// Declaration of public function to print dog's description
public function getDogDescription() {
// Here we call the protected getDescription() method of parent class Animal
$this->getDescription($this->animal);
}
}
// Creating an object of class Animal
$animal = new Animal();
// Creating an object of subclass Dog
$dog = new Dog();
/*
Trying to access protected variables and methods
*/
echo $animal->animal; // Cannot be accessed
$animal->getDescription("Dog"); // Cannot be accessed
echo $dog->animal; // Cannot be accessed
/*
We can call getDogDescription method,
in which we are calling a protected method
of Animal class
*/
$dog->getDogDescription();
?>

Output:

protected in php

After commenting line 34

Commenting line 34

After commenting lines 35 and 36

After commenting Lines

In this example, we are first declaring the main parent class Animal and initializing a protected variable as $animal which is an array containing names of 3 different animals. Next, we are also declaring a protected function in which we are giving a unique description to each of the animals in the array.

Since protected variables can be accessed using subclass, we are here creating another subclass Dog from the parent class Animal. Also to showcase that public functions can be accessed anywhere, we declare a public function to output variable dog’s description.

Next, we create an object of both classes Animal and Dog and try to access their variables which are protected. Hence for lines 40, 41 and 42, we get a fatal error telling that protected properties/methods/variables cannot be accessed. Hence we cannot access any variables outside of class Animal since all are protected.

Importance of protected in PHP

  • The protected modifier basically reduces the visibility of the variable/method and hence is more secure than public access modifier which can be accessed anywhere.
  • Only subclasses can access protected methods and not by any class.
  • The utility of the class is made very clear when we are making it as protected. This is really helpful when there is a bunch of data and we need to put a definite mark on this one.
  • Protected variables and members are public to the class in which they are declared and also it’s child class which inherits this property from the parent class.
  • It provides second level security, one less than private which is most secure and next to public modifiers that are not that secure.
  • It helps the developer describe the shareable members and non-shareable ones and helps confine them within the walls of the class.

Conclusion

Hence protected variables are those access modifiers that are used for controlling specifically defined variables or methods or properties in a class. It needs to be explicitly specified by prefixing and hence can be accessed only within its declared package and by a subclass that inherits from the parent package.

Recommended Articles

This is a guide to Protected in PHP. Here we discuss the Introduction, Example of a Protected Variable and Method and Importance of Protected in PHP. You can also go through our other suggested articles to learn more–

  1. Protected Keyword in Java
  2. PHP Array Functions
  3. Destructor in PHP
  4. Protected in C#

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

1 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • PHP Object Injection
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP list
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP strpos
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More