如何通过存取器机制实现对对象私有变量的安全读取与写入操作?

2026-04-05 05:328阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计188个文字,预计阅读时间需要1分钟。

如何通过存取器机制实现对对象私有变量的安全读取与写入操作?

php// 私有变量的写入与读取class Myinfo { private $Name; private $Age; private $Job;

function __call($funcName, $arArguments) { $opsType=substr($funcName, 0, 3); $opsKey=substr($funcName, 3); switch ($opsType) { case 'set': return ($this->$opsKey=$arArguments[0]); } }}

<?php //私有变量的写入与读取 class Myinfo{ private $Name; private $Age; private $Job; function __call($funcName,$arArguments){ $opsType=substr($funcName,0,3); $opsKey=substr($funcName,3); switch($opsType){ case 'set': return($this->SetAccessor($opsKey,$arArguments[0])); break; case 'get': return($this->GetAccessor($opsKey)); break; } return(false); } private function SetAccessor($opsKey,$value){ if(property_exists($this,$opsKey)){ if(is_numeric($value)){ eval('$this->'.$opsKey.'='.$value.';'); }else{ eval('$this->'.$opsKey.'="'.$value.'";'); } }else{ return(false); } } private function GetAccessor($opsKey){ if(property_exists($this,$opsKey)){ eval('$name=$this->'.$opsKey.';'); return($name); }else{ return(false); } } function __toString(){ return "Name:$this->Name<br>Age:$this->Age<br>Job:$this->Job<br>"; } } $wzy=new Myinfo(); $wzy->setName('wzy'); $wzy->setAge(22); $wzy->setJob('Student'); echo $wzy; ?>

如何通过存取器机制实现对对象私有变量的安全读取与写入操作?

本文共计188个文字,预计阅读时间需要1分钟。

如何通过存取器机制实现对对象私有变量的安全读取与写入操作?

php// 私有变量的写入与读取class Myinfo { private $Name; private $Age; private $Job;

function __call($funcName, $arArguments) { $opsType=substr($funcName, 0, 3); $opsKey=substr($funcName, 3); switch ($opsType) { case 'set': return ($this->$opsKey=$arArguments[0]); } }}

<?php //私有变量的写入与读取 class Myinfo{ private $Name; private $Age; private $Job; function __call($funcName,$arArguments){ $opsType=substr($funcName,0,3); $opsKey=substr($funcName,3); switch($opsType){ case 'set': return($this->SetAccessor($opsKey,$arArguments[0])); break; case 'get': return($this->GetAccessor($opsKey)); break; } return(false); } private function SetAccessor($opsKey,$value){ if(property_exists($this,$opsKey)){ if(is_numeric($value)){ eval('$this->'.$opsKey.'='.$value.';'); }else{ eval('$this->'.$opsKey.'="'.$value.'";'); } }else{ return(false); } } private function GetAccessor($opsKey){ if(property_exists($this,$opsKey)){ eval('$name=$this->'.$opsKey.';'); return($name); }else{ return(false); } } function __toString(){ return "Name:$this->Name<br>Age:$this->Age<br>Job:$this->Job<br>"; } } $wzy=new Myinfo(); $wzy->setName('wzy'); $wzy->setAge(22); $wzy->setJob('Student'); echo $wzy; ?>

如何通过存取器机制实现对对象私有变量的安全读取与写入操作?