Callback function to class in PHP

A short sample on how to attach a callback function to PHP class:

 
<?php
 
  function outside(&$p1, $p2){
    $p1 = "This comes from the outside";
    echo "Outside: $p2\n";
  }
 
  class test{
    var $_events = array();
 
    function attach($handler_name, $method_name) {
      $this->_events[$handler_name] = $method_name;
    }
 
    function execute(){
      $ename = 'event1';
      $intext = 'This comes from the inside';
      $outtext = '';
      if (isset($this->_events[$ename])){
        call_user_func($this->_events[$ename], &$outtext, $intext);
      }
      echo "test Class: $outtext\n";
    }
  }
 
  $test = new test();
 
  $test->attach('event1', 'outside');
  $test->execute();
 
?>
 

This script produces the following result:

Outside: This Comes from the inside
test Class: This comes from the outside

Post a Comment

Your email is never published nor shared. Required fields are marked *