21xrx.com
2025-03-23 01:27:47 Sunday
文章检索 我的文章 写文章
深入解析PHP中的A
2023-06-11 00:46:13 深夜i     10     0
PHP A 访问控制

PHP中的A是指访问控制修饰符,用于控制类中的成员变量和方法的访问权限。主要包括public、protected和private三种类型。下面是具体示例:

class Person{
  public $name; //公有属性,任何地方都可以访问
  protected $age; //受保护的属性,只有本类和子类可以访问
  private $gender; //私有属性,只有本类可以访问
  public function __construct($name, $age, $gender){
    $this->name = $name;
    $this->age = $age;
    $this->gender = $gender;
  }
  public function getName(){
    return $this->name;
  }
  protected function getAge(){
    return $this->age;
  }
  private function getGender(){
    return $this->gender;
  }
}
class Child extends Person{
  public function getAge(){
    return "Child's age is ".$this->age;
  }
}
$p = new Person("Tom", 20, "male");
echo $p->name; //输出Tom
echo $p->age;  //Fatal error: Uncaught Error: Cannot access protected property Person::$age in ...
$c = new Child("Lucy", 8, "female");
echo $c->getAge(); //输出Child's age is 8

通过以上示例,我们可以清晰地了解到PHP中A的用法和意义,以及public、protected和private的区别。掌握好访问控制,有助于我们写出高质量的PHP代码。

  
  

评论区