I am trying to make a function that counts how many times it has been called
Here is my code:
<?php
function print_calls() {
count(print_calls);
}
print_calls();
?>
I want it to display how many times the function is called like
print_calls(); // 1
print_calls(); // 2
print_calls(); // 3
Something like this?
<?php
function callCount(){
static $calls=0;
echo $calls++;
}
callCount();
?>
You can use a static variable for this:
function print_calls() {
static $callCount=0;
printf("%d\n", ++$callCount);
}
Note that this only keeps the counts for the current process, so if you use this in a web server the count will be reset for each page you access. If you need persistent counts, you would have to write it to a file or use a $_SESSION variable.
Global variables may be dangerous. Be carefoul.
You can define a variable as counter and a function that uses that external variable.
php > $counter = 0;
php > function ciao() { global $counter; $counter++; echo $counter; }
From now, ... each time you call that function it print the variable incremented. This happens because the scope of $counter is not local to the function but global to the file.
php > ciao();
1
php > ciao();
2
php > ciao();
3
php > ciao();
4
php > ciao();
5
Related
I am learning about static variables in PHP and came across this code in PHP manual.
<?php
function test() {
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
test();
}
$count--;
}
?>
I couldn't understand the purpose of last $count--;. So, I wrote a different version of the function below:
<?php
function test() {
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
test();
}
echo 'I am here!';
$count--;
}
test();
?>
The output of above code is:
12345678910I am here!I am here!I am here!I am here!I am here!I am here!I am here!I am here!I am here!I am here!
Why isn't the output just the line below because we go past the if condition only once.
12345678910I am here!
If we are going past the if condition multiple times, then shouldn't the output be:
1I am here!2I am here!3I am here!4I am here!5I am here!6I am here!7I am here!8I am here!9I am here!10I am here!
Thanks.
This is more about recursion than static variables. However:
Why the numbers are written out first and the text afterwards? Let's break each run of the function. For simplification, I'll only use example with 2 calls (if ($count < 2))
1st call starts, $count is incremented to 1
prints 1
Within the 1st call, the condition $count < 2 is met, so it calls test() (so that's going to be the 2nd call)
2nd call starts, $count is incremented to 2 (if it weren't static, it wouldn't keep the value from the higher scope)
prints 2
Within the 2nd call, the condition $count < 2 is NOT met, so it skips the if block
prints I am here! and ends the 2nd call
Now the 1st call is done running the recursive function so it continues
prints I am here! and ends the 1st call
When you're calling test() within the method that doesn't stop the execution of the rest of the code in the method.
The reason, as far as i can see, it doesn't output a number after each string of "i am here" is because you're calling the method test() before the output. So each time it's waiting for that method to complete before moving on to the next string.
If you were to move the $count echo to after it I believe it'd output as expected.
Does that answer your question at all?
I need a variable to be passed along several functions & if statements, i'm going to keep it short.
I start off with initializing a static counter which i will use to keep track of the case number in my mysql database;
static $counter = 1;
then i write my function in which i try to simply increment my global variable (this is in an if statement inside my function);
$counter++;
Now my code compiles and runs perfectly but the counter seems to never increment and give every case id 1.
Anyone know how i managed to mess this up?
EDIT (Current structure):
<?php
static $counter = 1;
function frontend($connection){
global $counter;
(...)
if(isset($_POST['submit'])){
(...)
if(isset($_POST['betaald'])){
$counter++;
}
}
} ...
Now this code makes a neat database of all i need except the counter which seems to be unchangeable.
Explain more about your code and see the example.
<?php
function keep_track() {
STATIC $count = 0;
$count++;
print $count;
print "<br />";
}
keep_track();
keep_track();
keep_track();
?>
This will produce the following result −
1
2
3
I have got this function in php that run and return a number. However what i want is the numbers to be add up each time the function is run.
Here is the code.
function sumRate(&$numbers) {
$sumArray="0";
if($numbers)
$sumArray=$numbers;
$countedArray=($sumArray+$numbers);
echo "<script>console.log('$countedArray')</script>";
}
example when button click Jquery Ajax sent the value to server side.
let say
sumRate("23");//console log 23
sumRate("20");//console log 20
but what I want is that each time the function is run console to log 43 instead of login each number
Weldone in advance
I'm not precisely sure of what your goal is, but if you would like to keep track of a running sum, one way is to use globals like so:
$sum = 0;
function sumRate($number) {
global $sum;
if($number) {
$sum += intval($number);
echo "<script>console.log('$sum')</script>";
}
}
sumRate("20");
sumRate("23");
Output:
<script>console.log('20')</script>
<script>console.log('43')</script>
Side note:
We cannot pass a value literal by reference. If we call sumRate("23") on a function with signature function sumRate(&$numbers), a fatal error will be thrown. Instead either pass in a variable, or omit the & from the signature.
Update:
On the client side if you would just like the final sum to be echo'd and not each number, then you can do this:
$sum = 0;
function sumRate($number) {
global $sum;
if($number) {
$sum += intval($number);
}
}
sumRate("20");
sumRate("23");
echo "<script>console.log('$sum')</script>";
Output:
<script>console.log('43')</script>
You will not see the input be added together because your input only lasts as long as the function call. You need a variable that can store this value, and is not limited to the scope of sumRate
Try
$mySum = 0;
sumRate($mySum, 23);//console log 23
sumRate($mySum, 20);//console log 43
function sumRate(&$sum, $number) {
if($number)
$sum +=$number;
echo "<script>console.log('$sum')</script>";
}
it'simple
<?php
function sumRate($numbers) {
global $countedArray;
$countedArray=$numbers+$countedArray;
return $countedArray;
}
echo sumRate(20);
echo sumRate(23);
?>
I have a question in my todays Exam in which I have to determine the output.
<?php
function statfun($x)
{
static $count=0;
$count += $x;
if ($count < 20) {
echo "$count <br>";
statfun(++$x);
} else {
echo "last num is $count";
}
}
statfun(2);
?>
The output is
2
5
9
14
last num is 20
I dont know why this is the output. I know it is due to the static member but each time it comes into the function the member $count is re-initialized.I had saw the documentation at Static Keyword.
But there is nothing written regarding the re-initialization of static variable? Can we re-initialize the static variable in PHP? With the same or any other value?
each time it comes into the function the member $count is re-initialized
This is incorrect. Static variables are initialized only once which is how statically declared variables differ from "ordinary" variables. So basically, you're assigning an initial value to $count. In multiple calls to statfun(), this static variable's value is preserved and can be reused.
From the manual, section "Using static variables":
A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.
Also look at the example-code in the manual. The difference stated there should answer your question.
when you pass 2 count is set to 2
with $count+=$x;
then you have called statfun(++$x) which is $x+1 and that is 2+1=3
so now $count will be $count+3 and that is 5, and then you call statfun with the value of 3 then $count will $count+(3+1) = 9 and so on and so on
static variable will hold its state. So if you call it like this
So basically static variable will hold its value and will not be re-initialized.
The situation:
index.php:
<?php
include("foo.php");
include("baz.php");
foo("bar.php");
?>
baz.php:
<?php
$x = 42;
?>
foo.php:
<?php
function foo($p) {
include_once($p); // please dont mind the inclusion hole
}
?>
bar.php:
<?php
echo $x;
?>
Zend notice: Undefined variable: x
Placing global $x; in bar.php removes the notice, but I understand why there is a notice about this in the first place.. Doesn't include pretty much work like including C headers? It would mean that the interpreted code would look like this:
<?php
function foo($p) {
include_once($p); // please dont mind the inclusion hole
}
$x = 42;
// this however, is included by a function...
// does the function's scope influence the stuff it includes?
echo $x; // undefined variable
?>
My editor is the Eclipse/Zend package.
I'm no expert, so please don't flame me if I'm wrong, but I think the file called by include_once or require_once is called in the context of the caller. Since function foo() won't know about $x then neither will any of its called includes. You could experiment by 'declaring' $x inside function foo() with the same setup as above.
I get a bunch of those notices since I'm almost allways goes with "$o .= 'foo'" without any definition. I'm just hiding them with error_reporting(E_ALL ^ E_NOTICE), but I don't know if it's the optimal way in this case.
It doesn't work even if the variable and the function are in the same file.
1 <?php
2
3 $x = 3;
4
5 function t()
6 {
7 echo $x;
8 }
9
10 t();
Prints nothing.
But add a global
1 <?php
2
3 $x = 3;
4
5 function t()
6 {
7 global $x;
8 echo $x;
9 }
10
11 t();
and you can see "3".
In a function you can't see global variables unless you declare it.
yes its the function scope that is causing your issues
if you replace
foo("bar.php");
with
include("bar.php");
you'll see that everything works fine because it puts it into the current scope and not functions scope