Search code examples
phpvariablescopyinstanceon-the-fly

Copy a function on the fly PHP


I'm working on a project which requires a function to be copied & executed on the fly and variables in it needs to be replaced on the fly too.

A simple example will be like this:

function myfunction()
{
    $abc = $_SESSION['abc'];
    return $abc;
}

I want to be able to call myfunction1() which does NOT physically exist in the code but does exactly the samething as the one above except it now take values from my custom variable so it'll look like this:

 function myfunction1()
 {
     $abc = $myCustomVariable;
     return $abc;
 }

Any one help pls?


Solution

  • The more you describe how convoluted your function is, the more it sounds like a perfect candidate for an object with injected dependencies.

    For instance, you could have (just going to describe the basic interfaces here):

    class myClass
    {
        public function __construct($provider DataProvider)
        {
            $this->provider = $provider;
        }
    
        // Please name this something better
        public function doStufferer()
        {
            if ($this->provider->hasParam('foo'))
            {
                return $this->provider->getParam('foo');
            }
        }
    }
    
    class SessionProvider implements DataProvider
    {
        // Session specific stuff
    }
    
    class OtherProvider implements DataProvider
    {
        // Other provider stuff
    }
    
    interface DataProvider
    {
        public function getParam($key);
        public function hasParam($key);
        public function setParam($key, $value);
    }
    

    You can then use it like this:

    $dataProcessor = new myClass(new SessionProvider);
    // OR $dataProcessor = new myClass(new OtherProvider);
    $dataProcessor->doStufferer();
    

    Please take a look at PHP Classes and Objects and the other related topics.