Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAman Kumar
10,444 PointsCan i access variables of parent class using parent:: keyword ??
In PHP.net, There is an explanation about parent keyword
" You may find yourself writing code that refers to variables and functions in base classes. This is particularly true if your derived class is a refinement or specialisation of code in your base class.
Instead of using the literal name of the base class in your code, you should be using the special name parent, which refers to the name of your base class as given in the extends declaration of your class. "
But i am unable to use the parent keyword to access the property of the class
<php
class Fish
{
public $common_name = 'Mamba'
}
class Trout extends Fish
{
public function getInfo()
{
return parent::$common_name;
}
}
$brook_trout = new Trout();
echo $brook_trout->getInfo();
?>
Its giving an error
Fatal error: Access to undeclared static property: Fish::$common_name
Can anyone explain, Why ?
1 Answer
Chris McKirgan
5,666 PointsYour Trout class extends your Fish class, this means that all its properties are also inherited.
To access the common_name variable, simple call it as a member variable, in scope with your Trout class as follows:
$this->common_name;
If you were to have called the function statically, this would not have worked because the '->' operator only worked for instantiated objects.
Helpful similar question on stackoverflow: http://stackoverflow.com/questions/6456939/php-accessing-parent-class-variable