Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP override function of a single instance

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();
like image 473
marius Avatar asked May 03 '16 08:05

marius


People also ask

How do you overwrite a function in PHP?

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.

Does PHP support function overriding?

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.

Can we override properties in PHP?

Is it possible to override parent class property from child class? Yes.

Can we override constructor in PHP?

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.


1 Answers

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.

like image 153
dbf Avatar answered Oct 13 '22 00:10

dbf