The following code does not produce the output with the name Jock
. I suspect because in the class
Animal
the $name
is private
, but the construct is public
so should the subclass not be able to get the $name
from the construct. I do not want to make $name
public
.
class Animal{
private $name;
public function __construct($name) {
$this->name = $name;
}
public function Greet(){
echo "Hello, I'm some sort of animal and my name is ", $this->name ;
}
}
class Dog extends Animal{
private $type;
public function __construct($name,$type) {
$this->type = $type;
parent::__construct($name);
}
public function Greet(){
echo "Hello, I'm a ", $this->type, " and my name is ", $this->name;
}
}
$dog2 = new Dog('Jock','dog');
$dog2->Greet();
the private variable only accessed inside the same class, you need to use protected for the name variable in class Animal.
class Animal{
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function Greet(){
echo "Hello, I'm some sort of animal and my name is ", $this->name;
}
}
class Dog extends Animal{
private $type;
public function __construct($name,$type) {
$this->type = $type;
parent::__construct($name);
}
public function Greet(){
echo "Hello, I'm a ", $this->type, " and my name is ", $this->name;
}
}
$dog2 = new Dog('Jock','dog');
$dog2->Greet();
You are right: delete the private
variable or use protected
in the first line of the class animal
and you're fine.
class Animal{
protected $name; //see here!
public function __construct($name) {
$this->name = $name;
}
public function Greet(){
echo "Hello, I'm some sort of animal and my name is ".$this->name ;
}
}
$animal = new Animal("Gizmo");
$animal->greet(); //produces the desired result.
echo $animal->name; //this will throw an error - unable to access protected variable $name
$name
won't be public since it is an argument used in the public constructor and is therefore confined to the scope of that function. The property name
on the dog will be public however unless you use protected
.
Dots are used to concat strings. However echo
allows commas to output multiple expressions.
public function Greet(){
echo "Hello, I'm a ".$this->type." and my name is ".$this->name;
}
Also when using double quotes; you can put the variables inside the string:
public function Greet(){
echo "Hello, I'm a $this->type and my name is $this->name";
}
You could use setter & getter methods to help you modify and retrieve your instance variables without needing to declare them as public.
If you are using eclipse: Right click on the class > Source > Generate Getters & Setters
which will create functions for all of your variables as so:
public String getName(){return this.name;}
public String setName(String name){this. name = name; }
You could then use these methods to access and edit your class variables