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!

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


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

Dreamweaver Mac version
Visual web development tools

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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
