Simoroshka Simoroshka - 8 months ago 53
PHP Question

PHP: change a method behavior

I have an object with some protected fields and a method that uses them. The method doesn't do exactly what I need it to do, but I cannot change the original code since I am writing an add-on.
Is it somehow possible to extend the class and override the method so that I could call it on predefined objects of the original class? I thought about monkey patching but apparently it is not implemented in php.


You can override a method by extending the parent class, initiating the new class instead of the parent class and naming your method exactly the same as the parent method, that was the child method will be called and not the parent


class Foo {
    function sayFoo() {
        echo "Foo";

class Bar extends Foo {
    function sayFoo() {
        echo "Bar";

$foo = new Foo();
$bar = new Bar();

$foo->sayFoo() //Outputs: Foo
$bar->sayFoo() //Outputs: Bar