There are three access rights in PHP object-oriented (oop):
public: public Type
Features: Externally callable, internally callable, subclass callable
In subclasses, public methods or properties can be called through self::var, parent::method Call the parent class method
In the instance, you can call the public type method or property through $obj->var
protected: Protected type
Features: Not callable externally, 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
Features: not callable externally, internally Callable, not callable by subclasses
The attributes or methods of this type can only be used in this class. Private type attributes and methods cannot be called in instances of this class, subclasses, or instances of subclasses. Method
Code example
<?php //final类不能被继承,final类不能被重写 //public 外部可调用,内部可调用,子类可调用 //protected 受保护类 外部不可调用 子类可以调用 //private私有的 外部不可调用 子类不可调用 class human{ //公有的 public $money = 1000; //受保护的 protected $che = "bmw"; //私有的 private $flower = "meigui"; //调用公有类 public function t1(){ echo $this->money; } //调用受保护的 public function t3(){ echo $this->che; } //调用私有的 public function t5(){ echo $this->flower; } } class stu extends human{ //子类调用公有的 public function t2(){ echo $this->money; } //子类调用受保护的 public function t4(){ echo $this->che; } //子类调用私有的 public function t6(){ echo $this->flower; } } //实例化对象 $stu = new stu(); echo $stu->money; echo $stu->t1(); echo $stu->t2(); echo $stu->t3(); echo $stu->t4(); echo $stu->t5(); echo $stu->t6();
Supplement: The difference between self and parent
a). These two objects are commonly used in subclasses. Their main difference is that self can call public or protected properties in the parent class, but parent cannot call
b).self:: It represents the static members (methods and properties) of the current class and $ This is different, $this refers to the current object
For more related knowledge, please visit PHP Chinese website! !
The above is the detailed content of What is the difference between the three access permissions (oop) in php. For more information, please follow other related articles on the PHP Chinese website!