开发者

PHP and inheritance with private/public variables

I have a question about the way in which the output is displayed.

<?php

class Base
{
    private $privattrib = "Private Attribute1";

    function GetAttrib()
    {
        echo $this->privattrib;
    }
}

class Derived extends Base
{
    private $privattrib = "bute";
    function GetAttrib()
    {
        parent::GetAttrib();    
    }
}

$b = new Base();
$d = new Derived();
$d->GetAttrib();

?>

So for the code above I have a couple questions:

  1. When I call parent::GetAttrib(), does the value of $this (in the Base's GetAttrib() method) become a Base 开发者_JAVA技巧object now or is it still a Derived object?

  2. The ouput is "Private Attribute1". If $this refers to a Derived object, shouldn't the display be "bute" since the private attribute is overrided in the base class?

  3. If I change both privaattrib to public, the output is now "bute". Why is this?


Note that having the overridden version of GetAttrib call the base version isn't very useful; leaving it undefined in Base will give the same result.

  1. It makes sense to think of it as being an object of type Base, as you can't call any functions that are defined only in Derived, and if private any member variables are defined in both, it will use those from Base.

  2. No; since $privattrib is private, Base's version and Derived's version are completely independent.

  3. If you make the $privattrib member public, the line

    public $privattrib = "bute";

is a redefinition of $privattrib rather than a declaration of a new independent varaible.


It seems that when you declare the property as private it cannot be overridden by a derived class. If you declare it as public it can be overridden and directly accessed by other code. I think protected means that it can be overridden but is not accessible externally.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜