Home > Article > Backend Development > PHP privatea permission control
The content of this article is about PHP's private permission control, which has certain reference value. Now I share it with everyone. Friends in need can refer to it
//private permission control
// ===Code part 1===
class Human { public $mood = ''; // 心情,公有 private $money = 1000; // 钱,私有 public function showMoney() { return $this->money; } private function secret() { echo '我小时候偷吃过一块肉'; } public function tellMe() { $this->secret(); } } $lisi = new Human(); $lisi->mood = 'happy'; echo $lisi->mood,'<br >'; //钱定义为私有属性,在类Human{}外面调用,调用失败 //echo $lisi->money; //$lisi-money = 500; echo $lisi->showMoney(); echo '<br >';/* showMoney是公共的,在此行可以调用. showMoney中的 return $this->money; 这一句运行的环境是在 类{}的内部,因此有权限访问 money属性 *///$lisi->secret(); //报错$lisi->tellMe(); // 可以调用,因为在通过函数在类内调用的echo '<hr >';
/*
Summary: private permission control
can only be called within class {}.
Walk out {}, it cannot be adjusted.
*/
//Permission control bug
// ===Code part 2===
class Human2 { private $money = 1000; public function getMoney($people) { return $people->money; } public function setMoney($people) { $people->money -= 500; } }$zhangsan = new Human2();$lisi = new Human2();//echo $lisi->money; //报错// 让李四去打探张三的钱echo $lisi->getMoney($zhangsan),'<br >'; //1000// 让李四去改变张三的钱$lisi->setMoney($zhangsan); //减500echo $lisi->getMoney($zhangsan),'<br >'; //剩500print_r($zhangsan);
/*
The strange thing is that
zhangsan’s money should be affected by zhangsan calling getMoney and setMoney.
But the principle when talking about private permission control is Compliant:
That is:
The call of getMoney() public has the right
getMoney is in the class {} and has the right to read the private property money
The call of setMoney() public has The right
setMoney is in class {} and has the right to modify zhangsan’s private attribute money
*/
Related recommendations:
The above is the detailed content of PHP privatea permission control. For more information, please follow other related articles on the PHP Chinese website!