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.
Here is my code :
<?php
class MyClass
{
protected $variable = 'DEFAULT';
function __construct($newVariable)
{
$this->variable = $newVariable;
echo $this->variable;
}
}
class OtherClass extends MyClass
{
function __construct()
{
echo $this->variable;
}
}
$foo = new MyClass('MODIFIED'); // Output : MODIFIED
$bar = new OtherClass(); // Output : DEFAULT
?>
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.
Thanks in advance.
EDIT 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.
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.
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.
You're not redefining the variable, you're just setting it in the parents constructor. Call it and you've got what you need (see the comment in the code, it's one line only):
<?php
class MyClass
{
protected $variable = 'DEFAULT';
function __construct($newVariable)
{
$this->variable = $newVariable;
echo $this->variable;
}
}
class OtherClass extends MyClass
{
function __construct()
{
parent::__construct(); # <<--- do this
echo $this->variable;
}
}
$foo = new MyClass('MODIFIED'); // Output : MODIFIED
$bar = new OtherClass(); // Output : MODIFIED
?>
Even if you have two classes definition, the concrete instance will always be of one class. That one class can inherit from a parent class, but if you override methods (like you did with the constructor), the parents class method will not be called because it has been overridden. However with the parent
keyword you can access a parent's method from within the child.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With