Access parent’s parent variable and Access interface constant variable

// Access parent's parent variable
class Parent1 {
 const PARENT_NAME = "ramesh Song";
 const PARENT_AGE = "31";
 const PARENT_EMAIL = "ilovephp@gmail.com";
 protected $_normal_val = "HeHeHeHe";
}

class Parent2 extends Parent1 {
 public function __construct(){}
}

class Child extends Parent2 {
 public function __construct(){}

 public function getParentName(){
  return parent::PARENT_NAME;
 }

 public function getNormalVal(){
  return $this->_normal_val;
 }
}

$c = new Child();
echo $c->getParentName();
echo "br";
echo $c->getNormalVal();

/*
Output :
 ramesh Song
 HeHeHeHe
*/

// Access interface constant variable

interface Parent3 {
 const PARENT_NAME = "ramesh Song";
 const PARENT_AGE = "31";
 const PARENT_EMAIL = "ilovephp@gmail.com";
 //protected $_normal_val = "HeHeHeHe"; Error : Interfaces may not include member variables
}

class Parent4 implements Parent3 {
 public function __construct(){}

 public function getParentName(){
  //return parent::PARENT_NAME;  Error : current class scope has no parent
  return self::PARENT_NAME;
 }
}

class Child2 extends Parent4 {
 public function __construct(){}

 public function getParentName(){
  return parent::PARENT_NAME;

 }
 public function getParentAge(){
  return parent::PARENT_AGE;
 }
}

$d = new Parent4();
echo $d -> getParentName();
echo "br";
$e = new Child2();
echo $e->getParentName();
echo "br";
echo $e->getParentAge();

/*
Output :
 ramesh Song
 ramesh Song
 31
*/

0 comments:

Post a Comment