PHP 访问修饰符
PHP中有三种访问修饰符:Public(公共)、Private(私有)和Protected(受保护)。
Public - 使用这个访问修饰符的类成员可以从任何地方公开访问,甚至可以从类的作用域外部访问。
Private - 使用这个关键字的类成员只能在类内部访问。它通过类实例的引用来保护成员,防止外部类访问。
Protected - 与private相同,但允许子类访问受保护的父类成员。
示例1:Public
<?php
class demo
{
public name="Ajeet";
functiondisp()
{
echothis->name."<br/>";
}
}
class child extends demo
{
function show()
{
echo this->name;
}
}obj= new child;
echo obj->name."<br/>";obj->disp();
$obj->show();
?>
输出:
示例2:Private
<?php
classJavatpoint
{
private name="Sonoo";
private function show()
{
echo "This is private method of parent class";
}
}
class child extends Javatpoint
{
function show1()
{
echothis->name;
}
}
obj= new child;obj->show();
$obj->show1();
?>
输出:
示例3:Protected
<?php
classJavatpoint
{
protected x=500;
protectedy=100;
function add()
{
echo sum=this->x+this->y."<br/>";
}
}
class child extends Javatpoint
{
function sub()
{
echosub=this->x-this->y."<br/>";
}
}
obj= new child;obj->add();
$obj->sub();
?>
输出:
示例4:public、private和protected
<?php
classJavatpoint
{
public name="Ajeet";
protectedprofile="HR";
private salary=5000000;
public function show()
{
echo "Welcome : ".this->name."<br/>";
echo "Profile : ".this->profile."<br/>";
echo "Salary : ".this->salary."<br/>";
}
}
classchilds extends Javatpoint
{
public function show1()
{
echo "Welcome : ".this->name."<br/>";
echo "Profile : ".this->profile."<br/>";
echo "Salary : ".this->salary."<br/>";
}
}obj= new childs;
$obj->show1();
?>
输出: