views:

27

answers:

2

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 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?

A: 

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.

silvo
A: 

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.

James McLeod
Cool but doesn't your #1 answer clash with #3? For example, if both of those attribs are public now and I run the parent method, it will use the derived classe's public overrided attribute. Thus, the Base object can see a Derived member's property.I'm just being picky heh.
Ilya
I don't think the answers clash, since I was careful to specify that the Base version is used only for private member variables; the answer to 3 expands on this by pointing out the different behavior you get if the member variable is public.
James McLeod