0

Is it possible to do something like this:

class foo {
    private $private = 'A';
}

class bar extends foo {
    echo $this->private;
}

bar returns null...

I'd really like it if the variable $private wasn't accessible by the child classes, but I'm unsure that it's even possible based simply on the paradigm of classed based development.

Private properties DO NOT provide the functionality I'm looking for.

I understand that this isn't accurate PHP code, but it's just an example ;)

James Thompson
  • 1,027
  • 6
  • 16

2 Answers2

2

This is how it already works. See the documentation:

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

See an example here: http://codepad.org/Yz4yjDft

Private properties DO NOT provide the functionality I'm looking for.

To me seems it is exactly what you want. If not, please elaborate.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • after a bit of thought - our child class wasn't writing to the parent 'private' property - it was creating its own variable in that namespace because it doesn't know the parent variable exists. we tested it with parent::$private. Fun little case test for me ;) – James Thompson May 08 '11 at 04:25
0
class foo {
    protected $private = 'A';
}

class bar extends foo {
    function __construct() {
        echo $this->private;
    }
}
 new bar();

// will echo 'A' 

You just need to do your processing inside a function, you can't have echo just inside you class.

EDIT:

protected will let you use the variable only in descendent classes. if that is what you are looking for

Ibu
  • 42,752
  • 13
  • 76
  • 103