Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Unamed Variables in Function Call Static

Tags:

variables

php

So we call some function in PHP:

do_something('foodabaa');
function do_something($subject)
{
  static $pattern = '~foo~';
  return preg_replace($pattern, 'bar', $subject);
}

Is the replacement value bar static, or is it dynamic so each call to the function reinitializes it?

By all means add info about other programming languages besides PHP.

like image 381
gwillie Avatar asked Nov 11 '22 14:11

gwillie


1 Answers

From PHP documentation (Example #5):

function test()
{
    static $a = 0;
    echo $a."\n\r";
    $a++;
}

Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it.

So if you will call it twice:

test();
test();

Return will be:

0
1

Lets back to your example. There is same situation, $pattern will be initialized just once.

Inside C/C++

void foo()
{
    static int a = 0;
    printf("%d", a);
    x++;
}

int main()
{
    foo();
    foo();
    return 0;
}

Output will be:

0
1

That's the common behavior in many languages which are using static variables.

like image 105
Kasyx Avatar answered Nov 14 '22 23:11

Kasyx