0

How can a protected variable be accessed from a child Class if it has a different value?

Example to wrong access: parent::$_my gives error

class Father{
  protected $_my=array('a','b');
}

class Child{
   protected $_my=array('c','d');
  function __construct(){
   parent::__construct();
   $this->_my=array_merge(parent::$_my,$this->_my);
  }
}

Thanks, Yosef

2
  • 1
    If you want the class to inherit from another, you must use the extends keyword - like Class Child extends Father Commented Jan 30, 2011 at 22:08
  • 1
    Protected variables can be accessed by children, that's how it works? $_my in Child will overwrite the values set in Father Commented Jan 30, 2011 at 22:10

2 Answers 2

3

$this->_my will be inherited from the parent when you instantiate a subclass, so you simply need to use:

$this->_my = array_merge($this->_my, array('c','d'));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks,It what i write in my application know , but how can i call with parent?
As Chris mentioned, $_my is inherited from the parent, to the child. Its all the same and there is no "parent property". You access it like any other property via $this->_my.
1

There is something wrong with you design. You have already declared a variable that can be accessed by child inside parent.

Try adding values to already existing variable, rather than redefining it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.