php 修饰符 与 魔术方法public protected private
什么是修饰符
修饰符分为三种
- 最常用的 public 修饰符 表示 公共的 可被访问的方法
- protected : 受保护的方法
- private 私有的
Public 修饰符使用
/**
* Class Test
* 定义一个Test 类
*/
class Test {
public function index(){
echo '我是Test类下的 Index 方法';
}
}
echo (new Test)->index();
// 输入结果 我是Test类下的 Index 方法
访问结果:
我是Test类下的 Index 方法
protected 受保护的方法
/**
* Class Test
* 定义一个Test 类
*/
class Test {
protected $data = 'protected';
public function index(){
echo '我是Test类下的 Index 方法' . $this->data;
}
}
echo (new Test)->index();
访问结果:
我是Test类下的 Index 方法protected
但如果我问 跨类访问 $data
class Demo{
public function lists(){
$Test = new Test;
echo '我想访问Test下的$data :' . $Test->$data ;
}
}
echo (new Demo)->lists();
结果
我想访问Test下的$data :
以上测试 证明 我们想在 Demo 中调用 Test 下的受保护的$data 是不行的 但是我们可以访问 到 Index 方法
class Demo{
public function lists(){
$Test = new Test;
echo '访问Index :' . $Test->index() ;
}
}
echo (new Demo)->lists();
如果想在Demo 中调用 Test 的$data 方法 我们需要 去继承 Test
class Demo extends Test{
public function lists(){
echo '访问Index :' . $this->data ;
}
}
echo (new Demo)->lists();
// 返回结果 访问Index :protected
私有类 private
/**
* Class Test
* 定义一个Test 类
*/
class Test {
protected $data = 'protected';
private $res = 'private';
public function index(){
echo '我是Test类下的 Index 方法';
echo $this->res;
}
}
class Demo extends Test{
public function lists(){
// 访问受保护的类
echo $this->data;
echo "<br>";
// 访问 index 类
echo $this->index();
echo "<br>";
// 访问私有类
echo '访问私有类'.$this->res;
}
}
echo (new Demo)->lists();
结果
protected
我是Test类下的 Index 方法private
访问私有类
以上结果总结:
1、我们可以通过继承 Test 在Demo->lists 方法中 找到 受保护的类 也可以找到index 类 但是我们找不到 私有类 res
2、受保护的类 和 公共类 可以 在继承后 作为父级别 并且被子级别调用
3、私有类 只有在 Test 下的 方法中 才能被调用 不可被任何继承等方式调用