PHP Questions Home
Categories
Arrays
Files
Forms
Creating PDFs
PHP Errors
Functions
Images
MySQL
Numbers
Others
Strings
Website

PHP Forums
Forums Index
MySQL Forum
PHP Forum
Flash/Actionscript
Javascript
Web design

More PHP
PHP Functions
Top Questions
Ask a Question
PHP Interview Questions
PHP Jobs
Ecommerce
IT Questions
Business Websites

Sponsors

sponsor ad
My Salary
PHP Developer Salary
Advertise Here

How do I get a variable in a function to retain its value between calls?


The key here is to use the static keyword in your function declaration, so for instance:

<?php
function myfunc() { static $myfunctionvariable 1
echo 
"the number $myfunctionvariable\n";
$myfunctionvariable++;
}
myfunc(); //1
myfunc();//2
myfunc();//3
?>


The use of the static keyword means that it will only be assigned the value 1 once, so each time the function is called the number will increment by one. If you do not use the static keyword, each time the function is called the variable will be set back to 1 each time.

Copy the code and try calling the function a few times both with and without the static keyword to see the effect it has.




ASK A QUESTION

More functions PHP Questions

Can we use include ("abc.php") two times in PHP page "makeit.php" ?

I want to use the php include function to bring in a file that is related by $ref to this page and I cannot get it to use the $ref variable. my code line is where echo $ref is the property number basically it is a view of different properties an

Hi; I had an email from my hosting company which said that my account was hacked and one script in images folder is trying to send thousands of spams(file name : "/public_html/images/sm5vy7.php"). they blocked my account and asked me to check

How do I return a value from a function?

What is a function?



Custom Search