-1

I wanted to make a piece of code reusable and wanted to do it with objected oriented code.

Is there a way to 'plugin' an object oriented code in any way? (look at my example below to see what I mean)

class Insert {
    function insert_test($a, $b) {
          return  $a.$b;
    }
}
$Insert = new Insert();

$insertplugin = "$Insert->insert_test('abc', '123')"; // the plugin of object oriented code
include_once("reusablecode.php");


reusablecode.php:

$something =1;
if($something >0)
{
    $insertplugin;
}
Sol
  • 949
  • 1
  • 11
  • 23
  • 1
    What you are suggesting there wouldn't work and would likely throw an error (object to string conversion because of double quotes or similar). It looks like what you want to do is eval the code string. But I would highly advise against it as it is very hard to get this right and can easily leave you open to remote code execution vulnerabilities. – Jonathan Kuhn Mar 13 '17 at 20:41
  • Good to know. I'll just do another route. Would rather not have an exploit. – Sol Mar 13 '17 at 20:44
  • I think this is really good reference material. Not sure why the down vote. – Sol Mar 14 '17 at 19:32
  • while I didn't downvote, there are a couple thousand results on SO for `php eval` that cover most of what was said in this Q&A. – Jonathan Kuhn Mar 14 '17 at 21:04

1 Answers1

3

Technically yes you can, you could call eval($insertPlugin); to run the code stored in a string. You would need to use single quotes to prevent the $Insert variable being converted into a string when you set the $insertPlugin variable.

However This is generally considered evil (particularly if your code is constructed from user input) See here: When is eval evil in php?

It depends on what you actually want to vary in your "plugin" as to what the correct approach would be. One approach would be to create a class that encapsulates the functionality you want.

class Command{
   private $inserter;
   public function __constructor($inserter){
       $this->inserter=$inserter;
   }
   public function run(){
     $this->inserter->insert_test('abc', '123');
   }
}
$command = new Command(new Insert());


$something =1;
if($something >0)
{
    $command->run();
}

Another would be to use lambda functions:

$insertPlugin=function() use ($Insert) {

    $Insert->insert_test('abc', '123');
};


$something =1;
if($something >0)
{
    $insertPlugin();
}

It sounds like you should probably do some more reading on OOP - I think what you basically want is a 'Command' class http://www.fluffycat.com/PHP-Design-Patterns/Command/ see in particular the use of an abstract class to allow you to define multiple different commands (or "plugins" as you called it)

Community
  • 1
  • 1
Theo
  • 1,608
  • 1
  • 9
  • 16