How can I protect a class property from extending classes in PHP?
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 ;)
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.
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
精彩评论