Converting code with Anonymous functions to PHP 5.2

前端 未结 2 1715
醉酒成梦
醉酒成梦 2020-12-19 00:32

I have some PHP 5.3 code which builds an array to be passed to a view. This is the code I have.

# Select all this users links.
$data = $this->link_model-&         


        
相关标签:
2条回答
  • 2020-12-19 01:29

    Anonymous functions are great for ephemeral one-offs, like event listeners in patterns like Observer.

    However, since you've already formalized an interface (callbacks for rendering names, categories, creation dates, and a delete link) you may as well go the extra step of defining a 'renderer' interface that requires those 4 methods to be implemented. Instead of passing callbacks you'd pass a single renderer subclass to the view, which could then be used to call the appropriate methods. The view could also validate it by checking the parent class. That would still allow you to swap renderers in the spirit of portable, reusable OOP without requiring anonymous functions.

    Is there a situation where your callbacks would ever be coming from arbitrary code (e.g. plugins)? If not, there's really no benefit to making those callbacks anonymous. It might seem like you're saving a little namespace bloat, but you're also making it tougher to debug or document.

    0 讨论(0)
  • 2020-12-19 01:30

    You could call one of those function like so:

    $func = $callbacks[0];
    $func();
    

    Which also works with create_function() and using strings for named functions like so:

    function test() {
      echo "test";
    }
    $func = 'test';
    $func();
    
    $func = create_function('' , 'echo "test 2"; ');
    $func();
    

    Also, if the calling is done using call_user_func you can use array($object, 'func_name') to call a public method on an object or a class with array('Class_Name', 'func_name'):

    class Test {
      public static function staticTest() { echo "Static Test"; }
      public function methodTest() { echo "Test"; }
    
      public function runTests() {
        $test = array('Test', 'staticTest');
        call_user_func($test);
    
        $test = array($this, 'methodTest');
        call_user_func($test);
      }
    }
    
    $test = new Test();
    $test->runTests();
    
    0 讨论(0)
提交回复
热议问题