__sleep() and superclass properties [closed]

折月煮酒 提交于 2019-12-13 11:04:28

问题


Given two classes:

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

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

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

EDIT:
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.


回答1:


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;
   }
}



回答2:


Private properties are not visible to child objects. You will need to change the visibility of $prop1 to protected so B can access it:

protected $prop1;

From the manual:

Members declared as private may only be accessed by the class that defines the member.




回答3:


A private member is not visible by any code in child classes. You will need protected.



来源:https://stackoverflow.com/questions/6626227/sleep-and-superclass-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!