Something like a callback delegate function in php

前端 未结 3 1575
时光取名叫无心
时光取名叫无心 2020-12-16 13:44

I would like to implement something similar to a c# delegate method in PHP. A quick word to explain what I\'m trying to do overall: I am trying to implement some asynchron

3条回答
  •  攒了一身酷
    2020-12-16 14:19

    I was wondering if we could use __invoke magic method to create "kind of" first class function and thus implement a callback

    Sound something like that, for PHP 5.3

    interface Callback 
    {
        public function __invoke(); 
    }
    
    class MyCallback implements Callback
    {
        private function sayHello () { echo "Hello"; }
        public function __invoke ()  { $this->sayHello(); } 
    }
    
    class MySecondCallback implements Callback
    {
        private function sayThere () { echo "World"; }
        public function __invoke ()  { $this->sayThere(); }
    }
    
    class WhatToPrint
    {
        protected $callbacks = array();
        public function register (Callback $callback) 
        {
            $this->callbacks[] = $callback;
            return $this;
        }
        public function saySomething ()
        {
            foreach ($this->callbacks as $callback) $callback(); 
        }
    }
    
    $first_callback = new MyCallback;
    $second_callback = new MySecondCallback;
    $wrapper = new WhatToPrint;
    $wrapper->register($first_callback)->register($second_callback)->saySomething();
    

    Will print HelloWorld

    Hope it'll help ;)

    But I'd prefer the Controller pattern with SPL for such a feature.

提交回复
热议问题