Introduction to access modifiers in php (code example)

不言
Release: 2023-04-04 20:58:01
Original
3834 people have browsed it

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. .

Introduction to access modifiers in php (code example)

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.

Copy after login

Result

object(overlapFunc)#1 (1) {
    ["s":"overlapFunc":public] => int(2)
}
Copy after login

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.

Copy after login

Result

object(overlapFunc)#1 (2) {
    ["s":"overlapFunc":private] => int(2)
    ["s":"overlapFuncBase":private] => int(1)
}
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!