Jump to content

count each time the function runs


majortom84

Recommended Posts

Write a function Counter() that keeps track of the number of times it is called. This function should not take any parameters and return the number of times that it has been called.

Example:

echo Counter();//1

echo Counter(); //2

 

 

I think I would go like this...

 

$count = 0;

function Counter() {

  $count = $count + 1;

}

 

Is this too simple? Am I doing it wrong

Link to comment
https://forums.phpfreaks.com/topic/288955-count-each-time-the-function-runs/
Share on other sites

Jacques1 was hoping you would reply with something like

It doesn't output anything but I do get an error message about an undefined variable

If that's half true then you don't have your environment set up to tell you about problems: find your php.ini, set

error_reporting = -1
display_errors = on
and restart your web server. Then try the script and see what you get.

 

There's no output because Counter() doesn't return anything to output. You get the undefined variable warnings because $count, while defined outside the function, is not defined inside the function. You don't get that variable for free.

The global thing is one solution but you should avoid it. I personally would have suggested the static $count thing you have now.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.