Alex
Alex

Reputation: 68482

Array of functions

I was wondering if it's OK if I store a set of functions into a array like this

$f = array(
   'functions1' =>
     array(
      'somefunction',
       array($this, 'someclassfunction'),
       array($this, 'someotherfunction'),
     ),
   'functions2' =>
     array(
      'somefunction',
       array($this, 'someclassfunction'),
       array($this, 'someotherfunction'),
     ),

   ...

);

and call them later like:

foreach($f as $key => $func)
  call_user_func($func)...

If I do a print_r($f) I get a huge array with lots variables from all these functions. Does this affect performance somehow?

Upvotes: 4

Views: 1969

Answers (3)

Jon
Jon

Reputation: 437376

Generally it's fine. It might depend on how the array is populated -- if it's hardcoded, then you can't make it "too big" in practice. If it's dynamically generated, you might want to check how large it can get and if the size becomes a problem switch to an incremental processing approach.

You can get a good estimate of how much memory the array takes up by calling memory_get_usage twice in your script (before and after allocating the array) and calculating the difference.

Of course I 'm talking about the feasibility of this approach and not its advisability since your question doesn't ask about it or offer any related information.

Upvotes: 2

Mark Baker
Mark Baker

Reputation: 212412

You can do it. but it isn't particularly readable for anybody else trying to work through the code. It's also more awkward if you need to pass parameters to those functions, and to handle return values (and potential error conditions). I'd not recommend it for those reasons.

Upvotes: 2

runfalk
runfalk

Reputation: 1996

If $f is really big, it'll consume your RAM. print_r actually prints object properties as well. I can see you use $this multiple times, and that's likely why your output is huge. The PHP documentation reads:

print_r(), var_dump() and var_export() will also show protected and private properties of objects with PHP 5. Static class members will not be shown.

$this is only represented once in memory though, i.e. the performance overhead is low.

call_user_func itself isn't as fast as calling the function directly though.

Upvotes: 2

Related Questions