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!

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 English version
Recommended: Win version, supports code prompts!

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