Simoroshka
Simoroshka

Reputation: 349

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.

Upvotes: 0

Views: 258

Answers (4)

apokryfos
apokryfos

Reputation: 40653

Problem is, once you've loaded the class, you can't officially unload it, and you do need to load it in order to extend it. So it's pretty tied up. Your best bet is to either hack the original class (not ideal) or copy paste the original class definition into a new file:

class ParentClass {
      //Copy paste code and modify as you need to.
}

Somewhere after the bootstrapping of your framework:

spl_autoload_register(function ($class) {
      if ($class == "ParentClass") { //Namespace is also included in the class name so adjust accordingly
         include 'path/to/modified/ParentClass.php';
      }
},true,true);

This is done to ensure your own modified class will be loaded before the original one. This is extremely hacky so first check if the framework you're using has native support for doing this.

Upvotes: 0

Joshua Lawson
Joshua Lawson

Reputation: 376

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

Example:

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

Upvotes: 1

Tunbola Ogunwande
Tunbola Ogunwande

Reputation: 133

Try creating a child class that extends the base or parent class that the object currently derives from. Create a new method with exactly the same name as the method in the Parent class and put your logic in there. Now instantiate your object from your new class, you would have succeeded in overriding that particular method and still have access to the methods and properties of the base class.

Upvotes: 0

Haresh Vidja
Haresh Vidja

Reputation: 8496

I hope below stategy will be works. asume that class is Foo and method is bar(). for override bar() method you have to make customFoo class as mentioned below.

class CustomFoo extends Foo{
    public function bar(){
        parent::bar();
    } 
}

I dont know actually what you need because you dont have explained in detail. Still I have tried my best. :)

Upvotes: 0

Related Questions