Jump to content

Archived

This topic is now archived and is closed to further replies.

atitthaker

Problem with derived class

Recommended Posts

I have the code as given below:
<?php
class ABC {
    function printValue()
    {
        print("This value shall be printed" . $this->x);
    }
}
class BCD extends ABC {
    private $x=10;
}

$bcd=new BCD;
$bcd->printValue();

?>

But when I try to access printValue function from the paren class it gives me error...

[color=red]Fatal error: Cannot access private property BCD::$x in /var/www/html/trainingweb/modules/test/TestAtitProblem.php on line 5[/color]

As the public method of ABC would be extended to BCD, it shall have access to its own member.

Plz help...

Share this post


Link to post
Share on other sites
This is much the same answer as to your other question variables declared as private are not available to any other class....they are not inherited.

Share this post


Link to post
Share on other sites
But as BCD is extending ABC so it shall not have access to *public* method of ABC and as I am instantiating object of class BCD it can access private member through ABC's (but now extended in BCD) access method.
Isn't it?
???

Share this post


Link to post
Share on other sites
My host is still running php 4 so I can't personally test but I'm pretty sure if you change it protected or public it would work.

Share this post


Link to post
Share on other sites

When referring to $this->x in ABC the x variable has to be local to that class, in your example it is not.  x is local to BCD since it is declared as private.

 

To fix this, change private $x=10; to public or protected (as mentioned above)

 

Share this post


Link to post
Share on other sites

Gah, didn't see the OP date.  @neta1o, don't resurrect 4 year old threads.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.