PHP中有三种访问修饰符,可以达到访问控制额效果分别是:
public(--公共的--)public的类成员可以被自身、子类和其他类访问
protected(--受保护的--)protected的类成员只能被自身和子类访问
private(--私有的--)private的类成员只能被自身访问
---------------分割线--------------分割线--------------
<?php class Human{ public $name; protected $age; private $money; public function __construct($name,$age,$money) { $this->name = $name; $this->age = $age; $this->money = $money; } //public方法 public function sayName(){ var_dump($this->name); } //protected方法 protected function sayAge(){ var_dump($this->age); } //private方法 private function sayMoney(){ var_dump($this->money); } } $man = new Human('Tom',18,1000); echo $man->name; //Tom //echo $man->age; //Cannot access protected property Human::$age //echo $man->money; //Cannot access private property Human::$money $man->sayName(); //string(3) "Tom" //$man->sayAge(); //Call to protected method Human::sayAge() from context //$man->sayMoney(); //Call to private method Human::sayMoney() from context
实例化的对象,我们只能访问公开的属性和方法,受保护的、私有的属性和方法在外部是不可能访问和修改的