4

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?

1
  • Please stop writing tags in titles. Commented May 9, 2011 at 10:49

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

3 Comments

Respectfully, I disagree. To that extent I'd say you don't recommend it for those reasons. ;)
Disagree with the readability? Or with the passed arguments, return values and potential exceptions?
I'm retracting my previous comment. In thinking it through more I have to agree with you. +1
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.