Home > Backend Development > PHP Tutorial > PHP privatea permission control

PHP privatea permission control

不言
Release: 2023-03-24 20:32:02
Original
1826 people have browsed it

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,&#39;<br >&#39;;
//钱定义为私有属性,在类Human{}外面调用,调用失败
//echo $lisi->money;
//$lisi-money = 500;
echo $lisi->showMoney();
echo &#39;<br >&#39;;/*
showMoney是公共的,在此行可以调用.
showMoney中的 return $this->money;
这一句运行的环境是在 类{}的内部,因此有权限访问 money属性
*///$lisi->secret(); //报错$lisi->tellMe(); 
// 可以调用,因为在通过函数在类内调用的echo &#39;<hr >&#39;;
Copy after login

/*
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),&#39;<br >&#39;;
 //1000// 让李四去改变张三的钱$lisi->setMoney($zhangsan); 
 //减500echo $lisi->getMoney($zhangsan),&#39;<br >&#39;; 
 //剩500print_r($zhangsan);
Copy after login

/*
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:

PHP this binding

The above is the detailed content of PHP privatea permission control. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template