Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

injecting codes (methods) into class?

Tags:

oop

php

Take this simple code:

class MyClass {
   public $customFunction = array();

   public function run($name){
       call_user_func($this->customFunction[$name]);
   }
}

//> Usage:

$c = new MyClass();
$c->customFunction['first'] = function (){ /* some code*/ };

$c->run('first');

This cose works as excpted. I add that function to $customFunction and then i can call it form run(); method.

The problem comes when in my injected function I try to do something object-related, for example if i add this function:

$c->customFunction['first'] = function(){ $this->callsomemethod(); }

When i call the run(); method PHP says I can't use $this in a static context.

Do I have some way to inject those function and be able to use the object method?

(Note: of course my class is just an example, I need this for a scope)
Thanks

Thanks to Mario, here the solution I will use:

public function run($name) {
    call_user_func($this->customFunction[$name],$this);
}

At this point i just need to add function with a parm like this:

= function ($this) { /*some code*/};

And $this will emulate the object-context scope.


1 Answers

The error originates in the code you have shown as /* some code*/ in your example.

You assign an anonymous function here:

$c->customFunction['first'] = function (){ /* some code*/ };

And it remains just a function. It doesn't become a real method of the class. So using $this within it won't work.


Workaround: Pass your custom functions an $obj parameter, and have them use that instead of $this. (Really, just a quirky workaround; but doable.)

call_user_func($this->customFunction[$name], $obj=$this);

Or try classkit_method_add or runkit for a "proper" solution. - If available in your PHP.

like image 75
mario Avatar answered Nov 17 '25 08:11

mario



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!