동적변수와 정적변수와의 차이는 함수 안에서 반복문이나 재귀호출에 의해 수행되는 변수가 함수의 종료시까지 메모리에 할당해두는 것을 정적변수라 합니다.

변수명 앞에 static 구문을 추가해주면 정적변수가 됩니다.

<?php 
 function test1(){ 
     $a++; 
     echo $a; 
 } 

 function test2(){ 
     static $a; 
     $a++; 
     echo $a; 
 } 

 for($i=0; $i<=10; $i++){ 
     test1(); // 동적변수입니다. 
 } 

 echo "<br/>"; 

 for($i=0; $i<=10; $i++){ 
     test2(); // 정적변수입니다. 
 } 

 /* 
 결과: 
 11111111111 
 1234567891011 
 */ 
 ?>

<?php 
 function foo() { 
    static $bar; 
    $bar++; 
    echo "Before unset: $bar, "; 
    unset($bar); 
    $bar = 23; 
    echo "after unset: $bar\n"; 
 } 
 foo(); // 결과: Befor unset: 1, after unset: 23 
 foo(); // 결과: Befor unset: 2, after unset: 23 
 foo(); // 결과: Befor unset: 3, after unset: 23 
 ?>

0 댓글