기본문법

PHP에서 변수는 변수명 앞에 달러사인을 덧붙여 표현된다. 변수명은 대소문자를 구별한다.

PHP에서 변수명은 다음 규칙을 따른다. 유효한 변수명은 문자나 밑줄로 시작하고, 그 뒤에 문자, 숫자, 밑줄이 붙을수 있다. 정규표현식으로 표현하면 다음과 같다: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

Note: 여기서 문자는 a-z, A-Z, 그리고 127부터 255까지(0x7f-0xff) 바이트를 의미합니다.

Note: $this은 특수 변수로, 할당할 수 없습니다.

변수 관련 함수는, 변수 관련 함수 레퍼런스를 참고하십시오.

<?php
$var 
'Bob';
$Var 'Joe';
echo 
"$var$Var";      // outputs "Bob, Joe"

$4site 'not yet';     // invalid; starts with a number
$_4site 'not yet';    // valid; starts with an underscore
$täyte 'mansikka';    // valid; 'ä' is ASCII 228.
?>

기본값으로, 변수는 항상 값에 의해 할당되어야 합니다. 변수를 표현식으로 지정할때에 원래 표현식의 모든 값이 목표 변수로 복사된다. 이 말의 의미는 예를 들면, 어떤 변수값을 다른 변수로 지정한 후에, 그 변수중 어떤 하나를 변경하는것이 다른 변수에 영향을 미치지 않는다는 의미를 갖는다. 이런 종류의 지정에 대해서 표현식을 참고.

또한, PHP에서는 이와 다른 방법으로 변수에 값이 지정된다: 참조에 의한 지정. 이 용어의 의미는 새로운 변수가 원래 변수를 참조한다는 것이다.(즉, "원래 변수의 별명이 되는것" 이나 "가리키는 것") 새 변수의 변경은 원래 변수에 영향을 미치고, 그 반대도 가능하다.

참조에 의한 지정을 위해서는, 단순히 지정되는(소스 변수) 변수의 시작부분에 엠퍼센트(&)를 덧붙이면 된다. 예를 들면 다음 코드 예는 'My name is Bob'이 두번 출력된다.

<?php
$foo 
'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$bar "My name is $bar";  // Alter $bar...
echo $bar;
echo 
$foo;                 // $foo is altered too.
?>

주의할 것은 오직 이름이 부여된 변수만이 참조에 의해 지정된다는 것이다.

<?php
$foo 
25;
$bar = &$foo;      // This is a valid assignment.
$bar = &(24 7);  // Invalid; references an unnamed expression.

function test()
{
   return 
25;
}

$bar = &test();    // Invalid.
?>

PHP에서 변수를 초기화 할 필요는 없지만, 초기화는 매우 좋은 습관입니다. 초기화되지 않은 변수는 자료형과 사용되는 위치에 따라서 기본값을 가집니다 - 논리 기본값은 FALSE, 정수형과 소수형은 0, 문자열(echo등에서 사용)은 빈 문자열로 설정되고, 배열은 빈 배열로 설정됩니다.

Example #1 초기화되지 않은 변수의 기본값

<?php
// 설정되지 않고 참조되지 않은 (사용되지 않은) 변수; NULL 출력
var_dump($unset_var);

// 논리 사용; 'false' 출력 (이 구문에 대한 설명은 3항 연산자를 참고하십시오)
echo($unset_bool "true\n" "false\n");

// 문자열 사용; 'string(3) "abc"' 출력
$unset_str .= 'abc';
var_dump($unset_str);

// 정수 사용; 'int(25)' 출력
$unset_int += 25// 0 + 25 => 25
var_dump($unset_int);

// 소수 사용; 'float(1.25)' 출력
$unset_float += 1.25;
var_dump($unset_float);

// 배열 사용; array(1) {  [3]=>  string(3) "def" } 출력
$unset_arr[3] = "def" // array() + array(3 => "def") => array(3 => "def")
var_dump($unset_arr);

// 객체 사용; 새 stdClass 객체 생성 (http://www.php.net/manual/kr/reserved.classes.php 참고)
// 출력: object(stdClass)#1 (1) {  ["foo"]=>  string(3) "bar" }
$unset_obj->foo 'bar';
var_dump($unset_obj);
?>

초기화되지 않은 변수의 기본값에 의존하는 것은, 같은 변수명을 사용하는 파일을 포함하는 등에서 문제가 될 수 있습니다. 또한, register_globals를 켜놓은 상태에서 주요한 보안 위험입니다. 초기화되지 않은 변수를 사용할 때 E_NOTICE 등급의 오류가 발생하지만, 초기화되지 않은 배열에 원소를 추가할 때는 발생하지 않습니다. isset() 언어 구조로 변수가 초기화되었는지 확인 할 수 있습니다.

add a note add a note

User Contributed Notes 6 notes

up
66
jeff dot phpnet at tanasity dot com
13 years ago
This page should include a note on variable lifecycle:

Before a variable is used, it has no existence. It is unset. It is possible to check if a variable doesn't exist by using isset(). This returns true provided the variable exists and isn't set to null. With the exception of null, the value a variable holds plays no part in determining whether a variable is set.

Setting an existing variable to null is a way of unsetting a variable. Another way is variables may be destroyed by using the unset() construct.

<?php
print isset($a); // $a is not set. Prints false. (Or more accurately prints ''.)
$b = 0; // isset($b) returns true (or more accurately '1')
$c = array(); // isset($c) returns true
$b = null; // Now isset($b) returns false;
unset($c); // Now isset($c) returns false;
?>

is_null() is an equivalent test to checking that isset() is false.

The first time that a variable is used in a scope, it's automatically created. After this isset is true. At the point at which it is created it also receives a type according to the context.

<?php
$a_bool
= true;   // a boolean
$a_str = 'foo';    // a string
?>

If it is used without having been given a value then it is uninitalized and it receives the default value for the type. The default values are the _empty_ values. E.g  Booleans default to FALSE, integers and floats default to zero, strings to the empty string '', arrays to the empty array.

A variable can be tested for emptiness using empty();

<?php
$a
= 0; //This isset, but is empty
?>

Unset variables are also empty.

<?php
empty($vessel); // returns true. Also $vessel is unset.
?>

Everything above applies to array elements too.

<?php
$item
= array();
//Now isset($item) returns true. But isset($item['unicorn']) is false.
//empty($item) is true, and so is empty($item['unicorn']

$item['unicorn'] = '';
//Now isset($item['unicorn']) is true. And empty($item) is false.
//But empty($item['unicorn']) is still true;

$item['unicorn'] = 'Pink unicorn';
//isset($item['unicorn']) is still true. And empty($item) is still false.
//But now empty($item['unicorn']) is false;
?>

For arrays, this is important because accessing a non-existent array item can trigger errors; you may want to test arrays and array items for existence with isset before using them.
up
4
anisgazig at gmail dot com
3 years ago
clear concept of variable declaration rules and classification

variable declaration rules:

1.start with dollar sign($)
2.first letter of variable name comes from a-zA-z_
3.next letters of variable name comes from a-zA-Z0-9_
4.no space,no syntex

classification of variables:

Variable are mainly Two types
1.Predefined Variable
2.User Define Variable

Predefined Variable
There are 12 predefined variables in php 8
1.$GLOBALS
2.$_SERVER
3.$_REQUEST
4.$_FILES
5.$_ENV
6.$_SESSION
7.$_COOKIE
8.$_GET
9.$_POST
10.$http_response_header
11.$argc
12.$argv

User Define Variable
User Define variable are 3 types
1.variable scope
2.variable variables
3.reference variable

Variable Scope
variable scope are 3 types
1.local scope
2.global scope
3.static variable
up
-10
Anonymous
7 years ago
I highly recommend to use an editor that can list all variable names in a separate window.

The reason are typing errors in variable names.

<?php
$somename
= "nobody";
// Now we want to use $somename  somewhere
echo $somemane ;
?>
And wonder why it doesn't print "nobody".
The reason is simple, we have a typing error in $somename and $somemane is a new variable.

In this example it might be easy to find. But if you use variables to calculate some things, you might hardly find it and ask yourself why your calculation is always wrong.
With an editor that list all variable names in a separate window such "double" variables but with wrong typing can be easily found.

BTW:
It would have been better, if the PHP language would require to use some sort of keyword to define a variable the first time.
up
-24
baoquyen804 at gmail dot com
6 years ago
When examining the variable name with the regular expression [a-zA-Z_ \ x7f- \ xff] [a-zA-Z0-9_ \ x7f- \ xff] this will cause an error:

<?php
$name
="aa'1'";
if(!
preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/',$name))
    echo
$name.' is not a valid PHP variable name';
else
    echo
$name.' is valid PHP variable name';
// output aa'1' is valid PHP variable name
//but:
$aa'1' = 10; // error syntac
?>

instead use it ^[a-zA-Z][_]?[\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

<?php
$name
="aa'1'";
if(!
preg_match('/^[a-zA-Z][_]?[\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $name))
   echo
$name.' is not a valid PHP variable name';
else
    echo
$name.' is valid PHP variable name';
// output aa'1' is not valid PHP variable name
?>
up
-31
maurizio dot domba at pu dot t-com dot hr
13 years ago
If you need to check user entered value for a proper PHP variable naming convention you need to add ^ to the above regular expression so that the regular expression should be '^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'.

Example

<?php
$name
="20011aa";
if(!
preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/',$name))
   echo
$name.' is not a valid PHP variable name';
else
   echo
$name.' is valid PHP variable name';
?>

Outputs: 2011aa is valid PHP variable name

but

<?php
$name
="20011aa";
if(!
preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/',$name))
   echo
$name.' is not a valid PHP variable name';
else
   echo
$name.' is valid PHP variable name';
?>

Outputs: 2011aa is not a valid PHP variable name
up
-7
anisgazig at gmail dot com
3 years ago
$this is a special variable so we can not assign it.But Prior to PHP 7.1.0, indirect assignment such as variable variables are allowed.

$bd = "this";
$$bd = "CountryNickName";

echo $this;//allowed prior to PHP 7.1.0

but from the version of 7.1.0,it was allowed.
To Top