Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

This is what parameters are for, I think your looking todo something like this:

$myCustomVariable = 'Some value';


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

myfunction(); //returns $_SESSION['abc']
myfunction($myCustomVariable); //returns "Some Value"

The direct answer is eval which I do not recommend.


You could have your function accept a parameter, like this.

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

 // call it like...
 myfunction1($myCustomVariable);

If you need to access a variable, but the name is generated by dynamic code, you can use $GLOBALS.

 function myfunction1($name_of_var)
 {
     $abc = $GLOBALS[$name_of_var];
     return $abc;
 }

 // call it like...
 $myCustomVariable = 'a value'
 myfunction1('myCustom' + 'Variable');
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top