package access (OOP)

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
Hologram
Forum Newbie
Posts: 2
Joined: Mon Feb 15, 2010 12:43 pm

package access (OOP)

Post by Hologram »

Hi,
how you usually solve missing "package" access visiblity in php?

Let's say we have following code:

Code: Select all

 
class A {
    public $b;
 
    public function __construct() {
      $this->b = new B();
      $this->b->var = 0;
    }
}
 
class B {
  public $var;  // want to set its public visibility only for the package
}
 
how to disallow access to property $var from the outside?

Code: Select all

 
$a = new A();
$a->b->var = 1; //not good
 
Is there any pretty (in the name of OOP) solution to this? Or how is it commonly solved?
Thanks in advance.
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: package access (OOP)

Post by Darhazer »

In C++ you can set $var protected and A as a friend class, so A will have access to B's properties
In PHP you can set $var protected and use a decorator (class that extends B, accept B's instance in the constructor and provides getter/setter for B's $var). Of course, in this way anybody can use the decorator, but still you have some encapsulation on the access. But why you'd couple A and B?
Hologram
Forum Newbie
Posts: 2
Joined: Mon Feb 15, 2010 12:43 pm

Re: package access (OOP)

Post by Hologram »

Thanks for the reply.

It is possible to use this pattern also if the "primary" class contains another class let say C similar to B?
The reason for it is that these classes contain logicaly grouped properties (analogous to structs) and I don't want to mix them with the other ones. The only way they can be initialized is through the "primary" class A.
Post Reply