I'm revising my OOPs concepts in PHP. I have a simple php code here for practising visibility.
When i declare $name as private in Big_Animal,
1)Why it doesn't throw an error when i try to assign a different value for $name from outside the class (ie. $lion->name="King")?
2)Why it doesn't throw an error when i try to reassign $name in Lion class (ie. $this->name="John").
I'm confused coz as per my knowledge, private properties can only be accessed within the class that defines the property.
The other thing i'm not clear about is protected properties. As per my understanding, protected properties can be accessed only within the class itself and its child classes. Can it be accessed by its grandchild classes?
Thank you.
<?php
abstract class Big_Animal{
private $name="Mary";
abstract public function Greet();
public function Describe(){
return "name: ".$this->name;
}
public function __set($name,$value){
$this->name=$value;
}
public function __get($name){
return $this->name;
}
}
class Lion extends Big_Animal{
public function Greet(){
$this->name="John"; //no error for this
return " roar!";
}
public function Describe(){
return parent::Describe()." I'm a Lion!";
}
}
$lion = new Lion();
$lion->name="King"; //no error for this
echo $lion->Describe();
echo $lion->Greet();
?>