In javascript i know it is possible to simply override a class-method of a single instance but I am not quite sure how this is managable in PHP. Here is my first idea:
class Test {
public $var = "placeholder";
public function testFunc() {
echo "test";
}
}
$a = new Test();
$a->testFunc = function() {
$this->var = "overridden";
};
My second attempt was with anonymous function calls which unfortunately kills the object scope...
class Test {
public $var = "placeholder";
public $testFunc = null;
public function callAnonymTestFunc() {
$this->testFunc();
}
}
$a = new Test();
$a->testFunc = function() {
//here the object scope is gone... $this->var is not recognized anymore
$this->var = "overridden";
};
$a->callAnonymTestFunc();
To override a method, you redefine that method in the child class with the same name, parameters, and return type. The method in the parent class is called overridden method, while the method in the child class is known as the overriding method.
Function overloading and overriding is the OOPs feature in PHP. In function overloading, more than one function can have same method signature but different number of arguments. But in case of function overriding, more than one functions will have same method signature and number of arguments.
Is it possible to override parent class property from child class? Yes.
Explanation. In PHP, the only rule to overriding constructors is that there are no rules! Constructors can be overridden with any signature. Their parameters can be changed freely and without consequence.
In order to fully understand what you are trying to achieve here, your desired PHP version should be known first, PHP 7 is more ideal for OOP approaches than any previous version.
If the binding of your anonymous function is the problem, you can bind the scope of a function as of PHP >= 5.4 to an instance, e.g.
$a->testFunc = Closure::bind(function() {
// here the object scope was gone...
$this->var = "overridden";
}, $a);
As of PHP >= 7 you can call bindTo
immediately on the created Closure
$a->testFunc = (function() {
// here the object scope was gone...
$this->var = "overridden";
})->bindTo($a);
Though your approach of what you are trying to achieve is beyond my imagination. Maybe you should try to clarify your goal and I'll workout all possible solutions.
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