开发者

__sleep() and superclass properties [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this quest开发者_Python百科ion so that it can be reopened, visit the help center. Closed 11 years ago.

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.


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜