Summary of Knowledge Points on Access Modifiers in php

  • 2021-11-13 06:57:44
  • OfStack

Why do you need access?

Prevent overwriting variable names and function names

Let's look at the use of public under 1. public is the most extensive access qualifier that can be accessed from anywhere.

Suppose Mr. A develops overlapFuncBase and Mr. B inherits overlapFuncBase and creates the example of overlapFunc.


<?php
class overlapFuncBase {
  public $s = 1;
}
class overlapFunc extends overlapFuncBase { 
  public $s = 2;
}
$obj_overlap = new overlapFunc();
var_dump($obj_overlap);

Results


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

In B overlapFunc, I can use overlapFuncBase created by Mr. A, but override it because the variable name $s is the same.

So you need to access modifiers at this time.


<?php
class overlapFuncBase {
  private $s = 1;
}
class overlapFunc extends overlapFuncBase { 
  private $s = 2;
}
$obj_overlap = new overlapFunc();
var_dump($obj_overlap)

Results


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

The difference with code 1 is that we change the access modifier public to private before the variable $s.

private means that you can only access it in your own class.

Therefore, even if every class created by A has the same variable name, you can now get different results.

Type of access modifier

The access modifiers are private, protected, and public

The corresponding range increases in the following order

private → protected → public

There is another special access modifier called static, which you can use anywhere if you specify a class name.


Related articles: