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.
ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock TestsStart Your Free Software Development Course
Web development, programming languages, Software testing & others
There are 5 kinds of access modifiers in PHP:
- 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 Protected Variable and Method
Let us understand the usage and working of protected modifier in detail by taking a simple example below:
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:
After commenting on line 29 which is trying to call the protected method
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:
After commenting line 34
After commenting lines 35 and 36
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.
The above is the detailed content of Protected in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.
