开放的编程资料库

当前位置:我爱分享网 > PHP教程 > 正文

PHP实现在对象之外访问其私有属性private及保护属性protected的方法

本文实例讲述了PHP实现在对象之外访问其私有属性private及保护属性protected的方法。分享给大家供大家参考,具体如下:


public

表示全局的访问权限,类内部外部子类都可以访问;


private

表示私有的访问权限,只有本类内部可以使用;


protected

表示受保护的访问权限,只有本类或子类或父类中可以访问;

比较经典的用法示例如下:

<?php
 //父类
 class father{
 public function a(){
 echo "function a<br/>";
 }
 private function b(){
 echo "function b<br/>";
 }
 protected function c(){
 echo "function c<br/>";
 }
 }
 //子类
 class child extends father{
 function d(){
 parent::a();//调用父类的a方法
 }
 function e(){
 parent::c(); //调用父类的c方法
 }
 function f(){
 parent::b(); //调用父类的b方法
 }
 }
 $father=new father();
 $father->a();
// $father->b(); //显示错误 外部无法调用私有的方法 Call to protected method father::b()
// $father->c(); //显示错误 外部无法调用受保护的方法Call to private method father::c()
 $chlid=new child();
 $chlid->d();
 $chlid->e();
// $chlid->f();//显示错误 无法调用父类private的方法 Call to private method father::b()
?>

运行结果:

function a
function a
function c

在对象之外,php访问私有及保护属性实现方法如下:

class yunke
{
 protected $a = 55;
 private $b = 66;
 public function merge()
 {
 $result = clone $this;
 $result->a=88;
 $result->b=99;
 return $result;
 }
 public function show()
 {
 echo $this->a;
 echo $this->b;
 }
}
$test = new yunke;
$test->show();
$test2=$test->merge();
$test2->show();

输出:

55668899

更多关于PHP相关内容感兴趣的读者可查看本站专题:《
》、《
》、《
》、《
》、《
》、《
》及《

希望本文所述对大家PHP程序设计有所帮助。


您可能感兴趣的文章:

未经允许不得转载:我爱分享网 » PHP实现在对象之外访问其私有属性private及保护属性protected的方法

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏