Reputation: 1
So I have this code, see below. I am running an error while getting a protected value. Thought that protected values will be inherited. I was figuring out why we need to call parent::__construct()
, while we just can extend a class.
If you could tell me whats wrong and how can I do it the right way, that would be awesome.
<?php
/**
* DogWords
*/
class DogWords
{
protected $words = array('Wrr', 'Grr', 'Weeee', 'Houou');
}
/**
* Dog Class
*/
class Dog extends DogWords
{
protected $dogname = NULL;
protected $dogwords = NULL;
public function __construct($dogname)
{
$this->dogname = $dogname;
$this->dogwords = new DogWords;
}
public function bark()
{
echo $this->dogname . "; Bark, bark, bark...";
}
}
/**
* Poodle
*/
class Poodle extends Dog
{
}
$Amy = new Poodle('DogConstructor');
echo $Amy->dogwords->words[1]; // Fatal Error...
echo $Amy->bark(); // DogConstructor; Bark, bark, bark...
?>
Upvotes: 0
Views: 117
Reputation: 7009
According to the rule of OOP, a protected
member can only be accessed from inside the base class and the derived class(immediate and non-immediate) but not from anywhere else.
But here you are trying to access the protected member of class dog
i.e. dogwords
in echo $Amy->dogwords->words[1]
using the subclass poodle
's object i.e. Amy
. Hence according to the principle you cannot access it this way.
Upvotes: 0
Reputation: 7688
If you pretend to keep the variable to protected
, why just don't do the following:
class DogWords
{
protected $words = array('Wrr', 'Grr', 'Weeee', 'Houou');
}
/**
* Dog Class
*/
class Dog extends DogWords
{
protected $dogname;
protected $dogwords;
public function __construct($dogname)
{
$this->dogname = $dogname;
$this->dogwords = new DogWords;
}
public function bark()
{
return $this->dogname . "; Bark, bark, bark...";
}
}
/**
* Poodle
*/
class Poodle extends Dog
{
public function getDogWords()
{
return $this->dogwords->words;
}
}
$Amy = new Poodle('DogConstructor');
$words = $Amy->getDogWords();
var_dump($words[1]);
var_dump($Amy->bark());
Example: http://codepad.org/GsmmHxev
Upvotes: 1
Reputation: 23719
The error comes from this fact: "Members declared protected can be accessed only within the class itself and by inherited and parent classes".
http://www.php.net/manual/en/language.oop5.visibility.php
In order to access them, you need to make them both public:
class DogWords
{
public $words = array('Wrr', 'Grr', 'Weeee', 'Houou');
}
/**
* Dog Class
*/
class Dog extends DogWords
{
protected $dogname = NULL;
public $dogwords = NULL;
//... rest of the code
$Amy = new Poodle('DogConstructor');
echo $Amy->dogwords->words[1]; // Fatal Error...
echo $Amy->bark(); // DogConstructor; Bark, bark, bark...
?>
Now this prints: "GrrDogConstructor; Bark, bark, bark..."
Upvotes: 0
Reputation: 14233
Protected
members cannot be used outside the scope of the subclass , if you want to access it outside it should be declared as public
.
Please study from here docs
Upvotes: 2