Jump to content


Photo

Problem with derived class


  • Please log in to reply
5 replies to this topic

#1 atitthaker

atitthaker
  • Members
  • PipPipPip
  • Advanced Member
  • 52 posts
  • LocationBanglore, India

Posted 16 August 2006 - 04:29 AM

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

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

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

Plz help...
Beginner with PHP and need help

#2 DocSeuss

DocSeuss
  • Members
  • PipPipPip
  • Advanced Member
  • 73 posts
  • LocationTexas, USA

Posted 16 August 2006 - 05:48 AM

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.
"Unlimited budget? Great, for $5,000,0000 we will run your ad banner for one year"  ----Rasmus Lerdorf

#3 atitthaker

atitthaker
  • Members
  • PipPipPip
  • Advanced Member
  • 52 posts
  • LocationBanglore, India

Posted 16 August 2006 - 06:02 AM

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?
???
Beginner with PHP and need help

#4 DocSeuss

DocSeuss
  • Members
  • PipPipPip
  • Advanced Member
  • 73 posts
  • LocationTexas, USA

Posted 16 August 2006 - 06:12 AM

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.
"Unlimited budget? Great, for $5,000,0000 we will run your ad banner for one year"  ----Rasmus Lerdorf

#5 neta1o

neta1o
  • New Members
  • Pip
  • Newbie
  • 1 posts

Posted 01 December 2010 - 03:32 PM

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)


#6 KevinM1

KevinM1
  • Moderators
  • Snarkimus Prime
  • 5,248 posts

Posted 01 December 2010 - 06:26 PM

Gah, didn't see the OP date.  @neta1o, don't resurrect 4 year old threads.
Using 'global' is a sign of doing it wrong




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users