There are three types of PHP access permission modifiers: 1. public, which means shared, with the largest scope of permissions and can be accessed anywhere; 2. protected, which means protected and inherited, and can only be accessed by the class itself and Internal members of the class can be accessed; 3. private means private and can only be accessed within the braces of the class definition.
The operating environment of this article: Windows 10 system, PHP version 8.1, Dell G3 computer
There are three types:
public shared
protected protected, inherited
private private
Detailed introduction:
public:
Public types can be used inside the class, in subclasses, or outside the class without restriction
Features: externally callable, internally callable, subclass callable
In the subclass, you can call public methods or attributes through self::var, and parent::method calls the parent class method.
In the instance, you can call the public type through $obj->var. The method or attribute
protected:
Protected type can be used inside the class and subclasses, but cannot be used outside the class
Features: Not callable externally, but callable internally. Subclasses can call it
In subclasses, protected methods or properties can be called through self::var, and parent::method calls parent class methods
Methods or properties of the protected type cannot be called through $obj->var in the instance
private:
Private type, can only be used inside the class , cannot be used outside the class or in subclasses.
Features: Not callable externally, callable internally, not callable by subclasses
The attributes or methods of this type can only be used in this class, in instances and subclasses of this class, Private type properties and methods cannot be called in instances of subclasses
Examples are as follows:
When creating a method, if it is not specified, the default is public
age
"; } //方法2,公有方法,回答年龄 public function ask_age() { $this->show_age(); } //方法3,设置数据 function set_data($arr){ $this->no=$arr["no"]; $this->name=$arr["name"]; $this->gender=$arr["gender"]; $this->age=$arr["age"]; } } //实例化一个对象 $s=new EMBA_student; $arr=array("no"=>"1","name"=>"Qian Zhang","gender"=>"Female","age"=>"33","department"=>"商业营销"); $s->set_data($arr); //echo $s->age;//Fatal error: Cannot access private property EMBA_student::$age in C:\xampp\htdocs\v\v.php on line 47 //$s->show_age(); //Fatal error: Call to private method EMBA_student::show_age() from context '' in C:\xampp\htdocs\v\v.php on line 48 $s->ask_age(); ?>
Recommended Study: "PHP Video Tutorial"
The above is the detailed content of What are the php access permission modifiers?. For more information, please follow other related articles on the PHP Chinese website!