Home  >  Article  >  Backend Development  >  PHP 如何获取protected属性?

PHP 如何获取protected属性?

WBOY
WBOYOriginal
2016-06-23 14:16:424333browse

class userVo extends model {
  protected $userid = array(.....); 

  protected $username = array(.....);
  
  .........
}


class model{

 public function getVoProtectedProperties(){
 
  如何获取userVo(对象而不是类) 内的protected属性?
     $this指向子类实例 
 }
}



class Action {
  public function init(){
      $uservo = new userVo(); 
      $uservo->getVoProtectedProperties();
 }
}

-------------------------------------------------------------
不想使用: $class_date = new ReflectionClass(get_class($this)); 来得到属性。 
能不能直接得到对象的所有protected属性的字段的值。 


回复讨论(解决方案)


用魔术方法,不知道是不是你想要的
class userVo extends model {
  protected $userid = array(.....); 

  protected $username = array(.....);
  
  

private function __get($property_name)
{
if(isset($this->$property_name))
{
return($this->$property_name);
}else
{
return(NULL);
}
}

private function __set($property_name, $value)
{
$this->$property_name = $value;
}

}

不用反射的话,可以在userVo 类中添加一个方法getProp

public function getProp(){
    return get_class_vars(get_class($this));
}

不用反射,在类外是获取不到protected和private属性的

 get_class_vars() 没有办法取得字段的修饰限定符protected.


因为不能确定字段的名称。 我想要的是任意的VO类的protected字段。 所以目前的办法是:

$class_date = new ReflectionClass(get_class($this)); 
$properties = $class_date->getProperties(ReflectionProperty::IS_PROTECTED);


但是我总是觉得:为什么不能从对象里面直接得到 protected字段的值呢?
是不是从安全原因考虑的? 

如果不想用反射的话,每个VO类多加个数组,数组的内容就是protected的属性名,直接返回这个数组。

属性名本身就只能靠反射返回,按照编程的思路上来说,属性名应该是具名的,而按照你设计的目的来说,属性名非具名,还要靠一定的逻辑去获取,这本身是不是存在设计上的缺陷呢?

 'id',		'username' => 'username',	);		// 而这个对象中完全可以用$this->prote['userid']来代替$this->userid}class model{	protected $prote = null;	public function getVoProtectedProperties(){		if(is_array($this->prote)) {			return array_keys($this->prote);		}	}}class Action {  public function init(){      $uservo = new userVo();       $uservo->getVoProtectedProperties();	  // 这里如果想用$uservo->userid的话,完全可以用魔术方法来实现 }}

protected 保护模式 只在类本身及派生类中可访问

你的应用是在 父类中读取子类的受保护的数据,这本身就是不合规矩的(用反射太另类了)

如果是需要在类间传递数据,建议你设一个单例模式的 context 类做载体


父类读取子类的数据: 是因为有若干子类,继承自父类。 统一由父类解析,再将解析后的VO,交给表现层处理。

目的就是想: 配置一个VO, 增删改查全部自动搞定。 所以VO内的属性只能动态获取来解析。
父类不仅要读取子类的数据,而且父类还要能够篡改或补充子类的属性。

感觉PHP的动态性非常强大,适合做快速开发平台。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn