I have this issue to solve: I create two classes where the second is an extends of the first and there I want to set and get an variable from the first class, but... I can't find the 'right' way to do it basically this:
class class_one {
protected $value;
private $obj_two;
public function __construct() {
$this->obj_two = new class_two;
}
public function firstFunction() {
$this->obj_two->obj_two_function();
echo $this->value; // returns 'New Value' like set in the class two
}
}
class class_two extends one {
public function obj_two_function() {
"class_one"->value = 'New Value';
}
}
How can I do this?
First class should not initialize the second, unless you're seeking Uroboros! Protected variables can be set by an extended class without any function support. Just go $this->protVariable = "stuff";
But you will need a function that may be protected to set ClassOne's private variable from the second class. Likewise a function must be made in ClassOne to actually retrieve its value.
class ClassOne {
private $privVariable;
protected $protVariable;
/**
*/
function __construct () {
}
/**
* This function is called so that we may set the variable from an extended
* class
*/
protected function setPrivVariable ($privVariable) {
$this->privVariable = $privVariable;
}
}
In the second class you can then call to parent::setPrivVariable()
to set the value using the parent function.
class ClassTwo extends \ClassOne {
/**
*/
public function __construct () {
parent::__construct ();
}
/**
* Set the protected variable
*/
function setProtVariable () {
$this->protVariable = "stuff";
}
/**
* see ClassOne::setPrivVariable()
*/
public function setPrivVariable ($privVariable) {
parent::setPrivVariable ( $privVariable );
}
}
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