fabian fabian - 5 months ago 13
PHP Question

Run the same function with two different preconditions?

Any ideas how to not DRY this? The idea is to run multiple function two times with two precondition (=sessions). I don't want to write the preconditions(=session var change) for both function (=doSomething and doAnything)

class Foo {
// run doSomething() 2x with different precondition (=Session var)
function bla() {
Session::put('year', 2016);
doSomething('hello');

Session::put('year', 2015);
doSomething('hello');
}


function yoo() {

// run doAnything() 2x with different precondition (=Session var)
Session::put('year', 2016);
doAnything('world');

Session::put('year', 2015);
doAnything('world');
}
}


It would be great to have something like this:

runWithYears(&doAnything('world'));

function runWithYears(func) {
Session::put('year', 2016);
// func should be called here
exec(func)

Session::put('year', 2015);
// func should be called here and will return a different result
exec(func)
}


Thanks

Answer

What you're looking for is called Anonymous functions.

Anonymous function allows you to declare it as a variable, which allows you to pass it to other functions as if it were any other variable.

Example - passing an anonymous function as a parameter & executing it

$myFunction = function (){
echo "I'm anonymous";
}

function runWithYears(func){
$func(); // Calling the anonymous function
}

runWithYears(myFunction);

Output: I'm anonymous

Comments