Note that there are some explanatory texts on larger screens.

plurals
  1. POChange the value of a protected variable for child class
    primarykey
    data
    text
    <p>I'm trying to do something that I thought would be quite simple but as I am relatively new to OOP in PHP I'm having a bit of trouble.</p> <p>Here is my code : </p> <pre><code>&lt;?php class MyClass { protected $variable = 'DEFAULT'; function __construct($newVariable) { $this-&gt;variable = $newVariable; echo $this-&gt;variable; } } class OtherClass extends MyClass { function __construct() { echo $this-&gt;variable; } } $foo = new MyClass('MODIFIED'); // Output : MODIFIED $bar = new OtherClass(); // Output : DEFAULT ?&gt; </code></pre> <p>I searched a lot of different threads and websites but haven't found how I could possibly pass the redefined value of $variable to the child class. Can someone guide me through it ? If there's a way.</p> <p>Thanks in advance.</p> <p><strong>EDIT</strong> Clarifying what is actually happening in the script I'm having this problem : I have a class that creates a form, and in that class there are several variables telling the functions in what environnement we are : if it's a multilanguage form or not, if I want a plain form or a structured one, parameters like that. And some of these environnement variables are modified through the execution of the class, by its functions.</p> <p>Now, because of the needs of my page, I have a child class dedicated to creating "select" fields. It inherits the core function of the main class to create fields and such but the child class takes several more parameters. Thing is, I would still like the select class to inherits the environnement parameters from the main class, in the state they are.</p> <p>As I'm typing this I realize the way I approached it may not be the right way to do it because when I look at my code I think there might be another way to do that. In my code I have two objects where I would need it to be only one, but I don't really know how I would put that actually.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload