Home >Backend Development >PHP Tutorial >Introduction to access modifiers in php (code example)
Protected in front of variables and functions is called access modifier. By appending access modifier, you can set the permission to access the function (access permission). In this article, we will introduce the usage of access modifier in PHP. .
Why do I need access?
Prevent overwriting variable names and function names
Let’s take a look at the use of public. Public is the most widely accessible from anywhere. Access qualifier.
Assume that Mr. A develops overlapFuncBase, and Mr. B inherits overlapFuncBase and creates overlapFunc example.
<?php class overlapFuncBase { public $s = 1; } class overlapFunc extends overlapFuncBase { public $s = 2; } $obj_overlap = new overlapFunc(); var_dump($obj_overlap);
Result
object(overlapFunc)#1 (1) { ["s":"overlapFunc":public] => int(2) }
In B overlapFunc, I can use overlapFuncBase created by Mr. A, but since the variable name $s is the same, it is overwritten.
So access modifiers are needed at this time.
<?php class overlapFuncBase { private $s = 1; } class overlapFunc extends overlapFuncBase { private $s = 2; } $obj_overlap = new overlapFunc(); var_dump($obj_overlap)
Result
object(overlapFunc)#1 (2) { ["s":"overlapFunc":private] => int(2) ["s":"overlapFuncBase":private] => int(1) }
The difference from the first code is that we change the access modifier public to private before the variable $s.
private means you can only access it within your own class.
Therefore, even if each class created by A has the same variable name, different results can now be obtained.
Types of access modifiers
Access modifiers include private, protected and public
The corresponding range increases in the following order
private→protected→public
There is another special access modifier called static. If you specify the class name, you can use it anywhere.
This article ends here. For more exciting content, you can pay attention to the relevant column tutorials on the php Chinese website! ! !
The above is the detailed content of Introduction to access modifiers in php (code example). For more information, please follow other related articles on the PHP Chinese website!