ltoso Posted February 3, 2011 Share Posted February 3, 2011 Hi, when i extend a class containing a private variable and then access the variable in the extended class it doesn't produce any error and works fine and when i access the variable using the object of the extended class it works even then, i think private variable should not be accessable in an extended class neither by object of that extended class here is the code <?php class textbox{ var $body_text, $body_text1; private $body_private="this is private value"; protected $body_protect="this is protected value"; function __construct($text_in, $text_out){ $this->body_text=$text_in; $this->body_text1=$text_out; } function display(){ echo "$this->body_text<br>"; echo "<i>"; echo "$this->body_text1</i><br>"; echo "$this->body_private<br/>"; echo "$this->body_protect<br/>"; } function test_new(){ echo "see if this private echo works"; } } $box=new textbox("any new value","any old value" ); $box->display(); $box->body_text="this is public thats why i can access it"; $box->body_text1="this is public thats why i can access it"; /*$box->body_private="this is private value changed"; //you will see we can't access the private and protected memebers from outside $box->body_protect="this is protected value changed"; */ $box->display(); $box->test_new(); class textboxbold extends textbox{ function __construct($text_on, $text_off, $text_get, $text_go) {$this->body_text=$text_on; $this->body_text1=$text_off; $this->body_protect=$text_get; $this->body_private=$text_go; } function display(){ echo "<b>$this->body_text</b><br>"; echo "<b>$this->body_text1</b><br>"; echo "<b>$this->body_protect</b><br>"; echo "<i>$this->body_private</i><br>"; } } $boxnew=new textboxbold("new Bold text", "text in bold","protected member","private"); $boxnew->display(); $boxnew->body_private="this is simple text taken from outside"; $boxnew->display(); $boxnew->test_new(); ?> please recommend, is it working as it should be Quote Link to comment Share on other sites More sharing options...
marcelobm Posted February 3, 2011 Share Posted February 3, 2011 Yes is working as it should be, because when you extend the class and call the constructor, this adds the values for the variables of its class in the case of the private and not the parents, then when you add outside of the object $boxnew->body_private = "this is simple text taken from the outside" what you are really doing is assigning that text to a public var body_private, if you do a var_dump at the end of your script on the $boxnew instance you will see what I mean Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.