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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

云客2009   2021-03-28 我要评论
想了解PHP实现在对象之外访问其私有属性private及保护属性protected的方法的相关内容吗,云客2009在本文为您仔细讲解PHP在对象之外访问其私有属性private及保护属性protected的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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程序设计有所帮助。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们