1

I need to run several functions at the same time. I had successfully implemented in C# by creating an ElapsedEventHandler and executing it when a timer gets elapsed. In this way I could run a number of functions at the same time (delegates). How can I do the same thing using php?

5lackp1x3l0x17
  • 349
  • 2
  • 7
  • 14

4 Answers4

4

Update

PHP supports multitasking now. See the pthreads API.


PHP does not have multi-threading. So you'd have to spawn another php process through CLI and run that script.

checkout these questions for more info:

Community
  • 1
  • 1
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • this is based on the assumption that you want to run the functions at the same time (simultaneouesly). – Anurag Dec 15 '09 at 10:43
  • 2
    Which is a fair assumption since the question explicitly says that. – Quentin Dec 15 '09 at 10:44
  • so you are saying that PHP does not have multi-threading and link to an answer where it says with a font of 30 that Multi-threading is possible in php. – Claudiu Creanga Jan 19 '16 at 18:30
  • 2
    @Claudiu - I answered this in 2009. The link I've added points to the question and not the answer. This [link](https://pecl.php.net/package/pthreads) shows all releases of the pthreads package that provides multithreading support with the earliest alpha release coming out in 2012. Sorry, I couldn't spare the time to go back and revise all my answers all the time as new developments happen, but you're most welcome to down vote this answer now. – Anurag Jan 19 '16 at 18:59
0

Something like this should work:

function foo() {
  echo "foo\n";
}

function bar() {
  echo "bar\n";
}

class multifunc {
 public $functions = array();
 function execute() {
  foreach ($this->functions as $function) $function();
 }
}

$test = new multifunc();
$test->functions[] = 'foo';
$test->functions[] = 'bar';
$test->execute();
Raynet
  • 463
  • 6
  • 16
-2

just create an array where you put all the functions you wanna run, then loop the array and run the functions.

foreach($functions as $func)
{
    $func();
}

is that what you wanna do?

tim
  • 1
-3

This is how you can imitate that:

   function runFuncs()
   {
     function1(); // run funciton1
     function2(); // run funciton2
     function3(); // run funciton3
     function4(); // run funciton4
     function5(); // run funciton5
   }

When you run runFuncs(); it runs all functions inside it.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • I cant do that, bcoz I dont know initially what functions will run. That will depend on the user. When I did created the same program in C# I used the following code: myTimer.Elapsed += new ElapsedEventHandler(function_name); by this I could add any function sort of dynamically... – 5lackp1x3l0x17 Dec 15 '09 at 10:30
  • I believe he means the timer stuff. – Alix Axel Dec 15 '09 at 10:42
  • @Sahil: You can use `register_tick_function()` and check for the right timestamp to execute. – Alix Axel Dec 15 '09 at 10:44