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

2025-05-29 0 78

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

public 表示全局的访问权限,类内部外部子类都可以访问;
private表示私有的访问权限,只有本类内部可以使用;
protected表示受保护的访问权限,只有本类或子类或父类中可以访问;

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34
<?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()

?>

运行结果:

?

1

2

3
function a

function a

function c

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21
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();

输出:

?

1
55668899

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

原文链接:http://blog.csdn.net/u011474028/article/details/52651205

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 PHP实现在对象之外访问其私有属性private及保护属性protected的方法 https://www.kuaiidc.com/93206.html

相关文章

发表评论
暂无评论