访问权限
在当今社会,我们每个人很注重自己的隐私,有些东西不想让外人知道,比如,我们的身份证号,收入情况等!但是,这一些是可以让我们的亲人知道的!我们的姓名确没必要不让别人知道,否则,人们咋找你,对吧?代码也是一样,有些代码,不想让其他代码可以随便使用,只能是某些可以让其他代码用,有的代码只能让子类用!这就是程序的访问权限,有3个:public:谁都可以访问;protected:子类和自己可以访问;private:只有自己可以访问,子类都不可以访问
例如:
class Father{
public $name = "父类的名称"; // 名字
private $secret = "父类的秘密"; // 秘密
protected $id = "110"; // 身份证
protected $salary = "10000"; // 收入情况
public function __construct(){
}
public function showInfo()
{
echo $this->id.PHP_EOL;
echo $this->secret.PHP_EOL;
echo $this->salary.PHP_EOL;
echo $this->name.PHP_EOL;
}
}
class Son extends Father{
public function __construct(){
$this->secret = "子类更改父类的秘密";
$this->id = "220";
}
}
class Other{
public function otherShow(Father $father)
{
echo $father->name.PHP_EOL;
echo $father->secret.PHP_EOL;
echo $father->id.PHP_EOL;
}
}
echo "以下是父级的输出-----------------------".PHP_EOL;
$father = new Father();
$father->showInfo();
echo "以下是子级的输出-----------------------".PHP_EOL;
$son = new Son();
$son->showInfo();
ECHO "以下是其他的输出-----------------------".PHP_EOL;
$other = new Other();
$other->otherShow($father);
以上将会输出以下内容:
以下是父级的输出-----------------------
110
父类的秘密
10000
父类的名称
以下是子级的输出-----------------------
220
父类的秘密
10000
父类的名称
以下是其他的输出-----------------------
父类的名称
PHP Fatal error: Uncaught Error: Cannot access private property Father::$secret in C:\Users\86150\Desktop\web\index.php:125
Stack trace:
#0 C:\Users\86150\Desktop\web\index.php(138): Other->otherShow(Object(Father))
#1 {main}
thrown in C:\Users\86150\Desktop\web\index.php on line 125
Fatal error: Uncaught Error: Cannot access private property Father::$secret in C:\Users\86150\Desktop\web\index.php:125
Stack trace:
#0 C:\Users\86150\Desktop\web\index.php(138): Other->otherShow(Object(Father))
#1 {main}
thrown in C:\Users\86150\Desktop\web\index.php on line 125
注:可以看到otherShow方法里的后面两个输出,报错了,提示"Cannot access private property Father::secret",中文的意思就是说:你没有权限去接触到private属性secret。但是,为什么son的输出没有报错,因为son的类是继承了Father,他可以继承了Father的所有的非private属性,this-\>secret = "子类更改父类的秘密";这里修改了private 属性secret,但是在调用showInfo时确还是父级的秘密;this->id="220",在调用showInfo时确是输出的是220,因为protected是可以被子类继承并修改的 。
再次强调:
public谁都可以访问;protected是可以被子类继承并修改的;private是完全私有的。这些规则同样也可以适用在类的方法里,你可以手动调置不同的访问权限调用一下,试试看!