开发者

Does a protected variable become private in an inherited class?

<?php 
class Example{
public $pub="public";
private $priv = "private";
protected $prot = "protected";
}
class SubClass extends Example{
}
$ex = new Example();
$sub = new SubClass();
/* called indiviually */
echo $sub->priv; // error
echo $sub->prot; // error

echo "<br/>";

echo $ex->pub; // works
echo $ex->p开发者_开发问答rot; // error 
?>

As you can see calling a protected variable with either parent class or subclass is throwing error . So what I can assume is: do something like, $prot acts like private modifier in parent class and we are not allowed to call it from outside the class block . and $prot variable when inherited into subclass it starts acting like private variable because even now it wasn't allowed to call it from outside . PS : not studied :: scope resolution operator yet . Used only -> arrow and $this


Protected variables are available inside the subclass but will throw an error in any other scope:

<?php 
class Example{
      public $pub="public";
      private $priv = "private";
      protected $prot = "protected";
}
class SubClass extends Example{
      function get_protected() {
           return $this->prot;
      }
}

$ex = new Example();
$sub = new SubClass();

/* called indiviually */
echo $sub->priv; // error
echo $sub->prot; // error

echo $sub->get_protected() // works

echo $ex->pub; // works
echo $ex->prot; // error 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜