Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- DS
- python
- CSS
- Algorithm
- Class
- control
- react
- function
- html
- MacOS
- php
- Java
- javascript
- DB
- Linux
- mysql
- architecture
- data structure
- DATAPATH
- instruction
- for
- MIPS
- github
- DoM
- XML
- while
- Pipelining
- web
- computer
- system
Archives
- Today
- Total
YYYEJI
[PHP] PHP 변수의 Scope 본문
728x90
PHP 변수의 scope에 대해서 알아보겠습니다.
변수를 function 밖에 선언했을 때
<!EOCTYPE html>
<body>
<h1>My first PHP page</h1>
<?php
$x = 10; // global scope
function myTest(){
echo "<p>Variable x inside funcion is: $x";
}
myTest();
echo "<p>Variable x outside funcion is: $x";
?>
</body>
→ Function 안에서는 변수 x에 접근할 수 없고, Funcion 밖에서만 변수 x에 접근할 수 있습니다.
변수를 funcion 안에 선언했을 때
<!EOCTYPE html>
<body>
<h1>My first PHP page</h1>
<?php
function myTest(){
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
</body>
→ Function 안에서만 변수 x에 접근할 수 있고, Funcion 밖에서는 변수 x에 접근할 수 없습니다.
Global 키워드
global 키워드를 사용하면 function 밖에서 선언된 변수를 function 안에서도 접근할 수 있습니다.
<!EOCTYPE html>
<body>
<h1>My first PHP page</h1>
<?php
$x = 5;
$y = 10;
function myTest(){
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y;
?>
</body>
$ Globals[index]
index를 느낌의 [ ]를 사용해서 global 변수를 불러올 수도 있습니다.
<!EOCTYPE html>
<body>
<h1>My first PHP page</h1>
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y;
?>
</body>
Static 키워드
<!EOCTYPE html>
<body>
<h1>My first PHP page</h1>
<?php
function myTest(){
static $x = 0;
echo $x." ";
$x++;
}
myTest();
myTest();
myTest();
?>
</body>
→ 함수 내부에서 선언된 변수는 함수 호출이 끝나면 사라지지만 static 키워드를 사용하면 사라지지 않고 값을 유지할 수 있습니다.
◡̈
'HTML(or XML) & CSS & JavaScript' 카테고리의 다른 글
[PHP] PHP 변수 type 확인 (0) | 2022.12.12 |
---|---|
[PHP] 문자열 합치기 (String concatenation) (0) | 2022.12.12 |
[PHP] PHP 출력문 (0) | 2022.12.12 |
[HTML] Table 열, 행 merge 시키는 태그 (0) | 2022.11.12 |
[HTML] Table 기본 태그 정리 (0) | 2022.11.12 |