3

I have

class Meat extends Food {
$var = Food::foodFunction…
}

I need to set $var for the Food class, how can I do that?

Thanks

4
  • Class Food is undefined in your example. Normally by how extending works, there actually is no class Food, there is only Meat in $this - but that should be no problem because Meat has everything Food has. Commented Jun 28, 2012 at 13:31
  • 3
    You need to set Food::$var and it is static? If so parent::$var = 'value' otherwise, you cannot set an instance variable for a parent. It merely exists in the child via $this->var Commented Jun 28, 2012 at 13:31
  • Code-Example: codepad.org/bqhtaVoJ , you are probably looking for the parent keyword. Commented Jun 28, 2012 at 13:38
  • Extremely unclear and doesn't answer to clarifications requested in the comments. I know it's an old question but -1 Commented Oct 24, 2017 at 9:03

2 Answers 2

5

If $var in the food class is a protected / public variable you just do with $this->var, if it's private you can't set it

Sign up to request clarification or add additional context in comments.

1 Comment

Beware that if you edit a parent variable, those edits are visible only inside the inherited class. It doesn't make lot of sense.
2

In the constructor or some other member function by using $this:

function __construct() {
    $this->var = Food::foodFunction();
}

Otherwise, you cannot initialize $var to anything that is not static.

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.