__sleep() 和超类属性 [英] __sleep() and superclass properties

查看:66
本文介绍了__sleep() 和超类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定两个类:

class A
{
   private $prop1;
}
class B extends A
{
   private $prop2;
   public function __sleep()
   {
      return array('prop1','prop2');
   }
}

这只会序列化 prop2 的值,因为它是 B 类的直接属性.

That will only serialize the value of prop2 as it's a direct property of class B.

如何让它输出从超类 A 继承的 prop1?

How can I get it to output the inherited prop1 from superclass A?


不定义 __sleep() 将显示序列化字符串中的 private 属性,而不会将它们设置为 protected.它们看起来像 A prop1,只是我不明白 是什么.


Not defining the __sleep() will show the private properties in the serialized string without setting them to protected. They look something like �A�prop1, only I cannot get what the � is.

推荐答案

显式调用父类的函数并追加结果:

Explicitly call the parent class's function and append the result:

class A
{
   private $prop1;
   public function __sleep()
   {
      return array('prop1');
   }
}

class B extends A
{
   private $prop2;

   public function __sleep()
   {
      $arr = parent::__sleep();
      array_push( $arr, 'prop2' );
      return $arr;
   }
}

这篇关于__sleep() 和超类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆