简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM