使用两个不同的前提条件运行相同的功能?

时间:2016-06-19 21:04:57

标签: php laravel laravel-5.2

任何想法如何不干这个?我们的想法是使用两个前提条件(= sessions)运行多次函数两次。我不想为这两个函数(= doSomething和doAnything)编写前置条件(= session var change)

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');
         }
     }

有这样的事情会很棒:

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)
}

由于

5 个答案:

答案 0 :(得分:1)

您要找的是匿名函数

匿名函数允许您将其声明为变量,允许您将其传递给其他函数,就像它是任何其他变量一样。

示例 - 将匿名函数作为参数&执行它

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

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

runWithYears(myFunction);
  

输出:我是匿名的

答案 1 :(得分:0)

你的问题必须多于此,但事实上,你可以在设置变量后一起运行你的功能

    Session::put('year', 2016);
    doSomething('hello');
    doAnything('world');

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

答案 2 :(得分:0)

编写代码如下:

    // run doSomething() and doAnything() 2x with different precondition (=Session var)

    Session::put('year', 2016);
    doSomething('hello');
    doAnything('world');

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

答案 3 :(得分:0)

http://php.net/manual/en/function.call-user-func.php

exec的来电替换为call-user-func应该具有入侵效果。

虽然我个人更喜欢这两种方法。

代码将是

runWithYears('doAnything' , 'world');

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

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

虽然如果提取到2种方法,它将更易于维护和使用

答案 4 :(得分:0)

感谢@Ante Gulin的帮助。

这是我使用闭包的概念验证。

new Sandbox();

class Sandbox {

    private $message;

    function __construct() {
        $this->first_method();
        $this->second_method();
    }

    private function first_method() {
        $test = function() {
            echo($this->message." peter");
        };

        $this->shout($test);

    }

    private function second_method() {
        $test = function() {
            echo($this->message." spiderman");
        };

        $this->shout($test);
    }


    private function shout($func) {
        $this->message = "hello";
        $func();

        $this->message = "cheerio";
        $func();
    }
}
相关问题