Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The value of a local variable of a function has to be retained over multiple calls to the function. How should that variable be declared in PHP

Tags:

php

The value of a local variable of a function has to be retained over multiple calls to the function. How should that variable be declared in PHP?

like image 427
OM The Eternity Avatar asked Dec 02 '22 05:12

OM The Eternity


1 Answers

using static. example:

function staticDemo() {
  static $x =1;
  echo $x;
  $x++;
}

the variable $x gets that static value the first time the function is called, afterwards it retains it's state.

example:

staticDemo(); // prints 1
staticDemo(); // prints 2
staticDemo(); // prints 3
like image 119
GSto Avatar answered Feb 16 '23 01:02

GSto