PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

定義済みの変数> <型の相互変換
Last updated: Fri, 18 Jul 2008

view this page in

変数

目次

基本的な事

PHP の変数はドル記号の後に変数名が続く形式で表されます。 変数名は大文字小文字を区別します。

変数名は、PHPの他のラベルと同じルールに従います。 有効な変数名は文字またはアンダースコアから始まり、任意の数の文字、 数字、アンダースコアが続きます。正規表現によれば、これは次の ように表現することができます。 '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

注意: ここで言うところの文字とはa-z、A-Z、127から255まで (0x7f-0xff)のアスキー文字を意味します。

注意: $this は特別な変数であり、ここに代入することはできません。

ヒント

ユーザレベルでの命名の手引き も参照ください。

変数関連の関数に関する情報については、 変数関数リファレンス を参照ください。

$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var";      // "Bob, Joe"を出力します。

$4site = 'not yet';     // 無効:数字で始まっている。
$_4site = 'not yet';    // 有効:アンダースコアで始まっている。
$täyte = 'mansikka';    // 有効:'ä' はアスキーコード228です。

デフォルトでは、変数に代入されるのは常にその値です。 これは、つまり、ある変数にある式を代入する際、元の式の 値全体がコピーされる側の変数にコピーされるということです。 これは、例えば、ある変数の値を他の変数に代入した後で、 これらの変数の1つを変更しても他の変数には影響を与えないという ことを意味します。この種の代入に関するより詳細な情報については、 を参照ください。

PHP には、変数に値の代入を行う別の方法も存在します。それは、 参照による代入 です。 この場合、新規の変数は元の変数を参照するだけです。 (言いかえると、元の変数の"エイリアスを作る"または元の変数を"指す") 新規の変数への代入は、元の変数に影響し、その逆も同様となります。

参照により代入を行うには、代入する変数(ソース変数)の先頭に アンパサンドを加えます。たとえば、次の簡単なコードは 'My name is Bob'を二度出力します。

<?php
$foo 
'Bob';              // 値'Bob'を$fooに代入する。
$bar = &$foo;              // $fooを$barにより参照
$bar "My name is $bar";  // $barを変更...
echo $bar;
echo 
$foo;                 // $fooも変更される。
?>

注意すべき重要な点として、名前のある変数のみが参照により代入できる ということがあります。

<?php
$foo 
25;
$bar = &$foo;      // これは有効な代入です。
$bar = &(24 7);  // 無効です。名前のない式を参照しています。

function test() {
   return 
25;
}

$bar = &test();    // 無効。
?>

PHP では変数を初期化する必要はありませんが、そのようにするのはとても よいことです。初期化されていない変数の値は、その型のデフォルト値 - FALSE、ゼロ、空の文字列あるいは空の配列となります。

例1 初期化されていない変数のデフォルト値

<?php
echo ($unset_bool "true" "false"); // false
$unset_int += 25// 0 + 25 => 25
echo $unset_string "abc"// "" . "abc" => "abc"
$unset_array[3] = "def"// array() + array(3 => "def") => array(3 => "def")
?>

初期化されていない変数のデフォルト値に依存すると、そのファイルを include している別のファイルで同名の変数が使用されていた場合などに 問題を起こします。また、register_globals が on の場合には重大なセキュリティリスク を抱えることになります。初期化されていない変数を使用すると、 E_NOTICE レベルのエラーが発生します。 しかし、初期化されていない配列に要素を追加する場合はエラーにはなりません。 変数が初期化されているかどうかの判断には、isset() を使用します。



定義済みの変数> <型の相互変換
Last updated: Fri, 18 Jul 2008
 
add a note add a note User Contributed Notes
変数
taliesin at gmail dot com
24-May-2008 10:14
or you could change the order of the if

function var_name(&$var, $scope=0)
{
    if (($old = $var) &&  (($var = $old) || true) && ($key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope))) return $key;
}
ned at wgtech dot com
22-May-2008 07:07
The function given in lower posts:

function var_name(&$var, $scope=0)
{
    if (($old = $var) && ($key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && (($var = $old) || true)) return $key;
}

has a nasty problem. If array_search fails the (($var=$old)||true) never gets evaluated, and rightly so, permanently changing the value of $var to 'unique#####value'.

How to fail the function:

$z=1;
var_name($z,array(1));

Easily fixed by adding an else:

function var_name(&$var, $scope=false)
{
    if ((($old=$var)||true)&&($key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && (($var = $old) || true)) return $key;
    else $var=$old;return false;
}

All better.
john dot t dot gold at gmail dot com
20-May-2008 05:03
To list all Variables for debug purposes use this:

<?php

echo '<table border=1><tr> <th>variable</th> <th>value</th> </tr>';
foreach(
get_defined_vars() as $key => $value)
{
    if (
is_array ($value) )
    {
        echo
'<tr><td>$'.$key .'</td><td>';
        if (
sizeof($value)>0 )
        {
        echo
'"<table border=1><tr> <th>key</th> <th>value</th> </tr>';
        foreach (
$value as $skey => $svalue)
        {
            echo
'<tr><td>[' . $skey .']</td><td>"'. $svalue .'"</td></tr>';
        }
        echo
'</table>"';
        }
             else
        {
            echo
'EMPTY';
        }
        echo
'</td></tr>';
    }
    else
    {
            echo
'<tr><td>$' . $key .'</td><td>"'. $value .'"</td></tr>';
    }
}
echo
'</table>';
?>
(rot13) yrvsrevx [at] jro [dot] qr
15-Feb-2008 03:00
err, the "($old = $var)" could also evaluate to false. Adding a "|| true" would make this overall to crude, I guess. It's better to leave it out of the expression.
(rot13) yrvsrevx [at] jro [dot] qr
15-Feb-2008 12:22
@cgorbit: This does not work, because "=" has a lower operator precedence than "||". The expression "($var = $old || true)" assigns true to $var. I corrected this and further shortened the function by putting "$old = $var" into the expression, too. :)
Note the parentheses that are necessary because of the operator precedence of "=" and "&&".

function var_name(&$var, $scope=0)
{
    if (($old = $var) && ($key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && (($var = $old) || true)) return $key;
}
cgorbit
05-Jan-2008 11:34
<?php
function var_name(&$var, $scope=0)
{
   
$old = $var;
    if ((
$key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && ($var = $old || true)) return $key
}
?>

Because $var may casts to false
alexandre at nospam dot gaigalas dot net
07-Jul-2007 05:13
Here's a simple solution for retrieving the variable name, based on the lucas (http://www.php.net/manual/en/language.variables.php#49997) solution, but shorter, just two lines =)

<?php
function var_name(&$var, $scope=0)
{
   
$old = $var;
    if ((
$key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && $var = $old) return $key
}
?>
jsb17 at cornell dot edu
20-Feb-2007 04:48
As an addendum to David's 10-Nov-2005 posting, remember that curly braces literally mean "evaluate what's inside the curly braces" so, you can squeeze the variable variable creation into one line, like this:

<?php
 
${"title_default_" . $title} = "selected";
?>

and then, for example:

<?php
  $title_select
= <<<END
    <select name="title">
      <option>Select</option>
      <option $title_default_Mr  value="Mr">Mr</option>
      <option $title_default_Ms  value="Ms">Ms</option>
      <option $title_default_Mrs value="Mrs">Mrs</option>
      <option $title_default_Dr  value="Dr">Dr</option>
    </select>
END;
?>
code at slater dot fr
25-Jan-2007 10:10
Here's a pair of functions to encode/decode any string to be a valid php and javascript variable name.

<?php

function label_encode($txt) {
 
 
// add Z to the begining to avoid that the resulting
  // label is a javascript keyword or it starts with a
  // number
 
$txt = 'Z'.$txt;
 
 
// encode as urlencoded data
 
$txt = rawurlencode($txt);
 
 
// replace illegal characters
 
$illegal = array('%', '-', '.');
 
$ok = array('é', 'è', 'à');
 
$txt = str_replace($illegal,$ok, $txt);
 
  return
$txt;
}

function
label_decode($txt) {
 
 
// replace illegal characters
 
$illegal = array('%', '-', '.');
 
$ok = array('é', 'è', 'à');
 
$txt = str_replace($ok, $illegal, $txt);
 
 
// unencode
 
$txt = rawurldecode($txt);
 
 
// remove the leading Z and return
 
return substr($txt,1);
}

?>
whoami
28-Dec-2006 06:14
what is so simple and flexible about these variable..? They're all the same thing -.-"
$var = whatever;

in fact is more complicated than:

String HelloWorld = hello;
giunta dot gaetano at sea-aeroportimilano dot it
04-Aug-2006 09:44
With php 5.1.4 (and maybe earlier?) take care about not using $this as a variable name, even when in the global scope or inside a plain function: the engine will prevent assigning any value to it...
molnaromatic at gmail dot com
20-May-2006 01:44
Simple sample and variables and html "templates":
The PHP code:
variables.php:
<?php
$SYSN
["title"] = "This is Magic!";
$SYSN["HEADLINE"] = "Ez magyarul van"; // This is hungarian
$SYSN["FEAR"] = "Bell in my heart";
?>

index.php:
<?php
include("variables.php");
include(
"template.html");
?>

The template:
template.html

<html>
<head><title><?=$SYSN["title"]?></title></head>
<body>
<H1><?=$SYSN["HEADLINE"]?></H1>
<p><?=$SYSN["FEAR"]?></p>
</body>
</html>
This is simple, quick and very flexibile
warhog at warhog dot net
28-Dec-2005 07:11
> Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

..is not quite true. You can, in fact, only declare variables having a name like this if you use the syntax <?php $varname = "naks naks"; ?>.. but in fact a variable can have moreless any name that is a string... e.g. if you look at an array you can have
<?php
$arr
[''];
$arr['8'];
$arr['-my-element-is-so-pretty-useless-'];
?>
.. by accessing the variables-namespace via {} you can have the same functinalities for all variables, e.g.

<?php ${''} = "my empty variable"; ?>

is a valid expression and the variable having the empty string as name will have the value "my empty variable".

read the chapter on "variable variables" for further information.
Mike at ImmortalSoFar dot com
25-Nov-2005 10:03
References and "return" can be flakey:

<?php
//  This only returns a copy, despite the dereferencing in the function definition
function &GetLogin ()
{
    return
$_SESSION['Login'];
}

//  This gives a syntax error
function &GetLogin ()
{
    return &
$_SESSION['Login'];
}

//  This works
function &GetLogin ()
{
   
$ret = &$_SESSION['Login'];
    return
$ret;
}
?>
david at removethisbit dot futuresbright dot com
10-Nov-2005 09:25
When using variable variables this is invalid:

$my_variable_{$type}_name = true;

to get around this do something like:

$n="my_variable_{$type}_name";
${$n} = true;

(or $$n - I tend to use curly brackets out of habit as it helps t reduce bugs ...)
ludvig dot ericson at gmail dot com
13-Oct-2005 12:33
On the previous note:

This is due to how evaluation works. PHP will think of it as:

$a = whatever $b = $c is
$b = whatever $c = 1 is

... because an expression is equal to what it returns.

Therefore $c = 1 returns 1, making $b = $c same as $b = 1, which makes $b 1, which makes $a be $b, which is 1.

$a = ($b = $c = 1) + 2;
Will have $a be 3 while $b and $c is 1.

Hope that clears something up.
Chris Hester
31-Aug-2005 01:09
Variables can also be assigned together.

<?php
$a
= $b = $c = 1;
echo
$a.$b.$c;
?>

This outputs 111.
Mike Fotes
09-Jul-2005 07:46
In conditional assignment of variables, be careful because the strings may take over the value of the variable if you do something like this:

<?php
$condition
= true;

// Outputs " <-- That should say test"
echo "test" . ($condition) ? " <-- That should say test" : "";
?>

You will need to enclose the conditional statement and assignments in parenthesis to have it work correctly:

<?php
$condition
= true;

// Outputs "test <-- That should say test"
echo "test" . (($condition) ? " <-- That should say test " : "");
?>
josh at PraxisStudios dot com
17-May-2005 09:06
As with echo, you can define a variable like this:

<?php

$text
= <<<END

<table>
    <tr>
        <td>
             $outputdata
        </td>
     </tr>
</table>

END;

?>

The closing END; must be on a line by itself (no whitespace).
user at host dot network
02-May-2005 01:17
pay attention using spaces, dots and parenthesis in case kinda like..
$var=($number>0)?1.'parse error':0.'here too';
the correct form is..
$var=($number>0)?1 .'parse error':0 .'here too';
or
$var=($number>0)?(1).'parse error':(0).'here too';
or
$var = ($number > 0) ? 1 . 'parse error' : 0 . 'here too';
etc..
i think that's why the parser read 1. and 0. like decimal numbers not correctly written, point of fact
$var=$number>0?1.0.'parse error':0.0.'here too';
seems to work correctly..
david at rayninfo dot co dot uk
26-Apr-2005 12:01
When constructing strings from text and variables you can use curly braces to "demarcate" variables from any surrounding text where, for whatever reason, you cannot use a space eg:

$str="Hi my name is ${bold}$name bla-bla";

which AFAIK is the same as

$str="Hi my name is {$bold}$name bla-bla";

zzapper
mike at go dot online dot pt
07-Apr-2005 05:18
In addition to what jospape at hotmail dot com and ringo78 at xs4all dot nl wrote, here's the sintax for arrays:

<?php
//considering 2 arrays
$foo1 = array ("a", "b", "c");
$foo2 = array ("d", "e", "f");

//and 2 variables that hold integers
$num = 1;
$cell = 2;

echo ${
foo.$num}[$cell]; // outputs "c"

$num = 2;
$cell = 0;

echo ${
foo.$num}[$cell]; // outputs "d"
?>
lucas dot karisny at linuxmail dot org
15-Feb-2005 12:42
Here's a function to get the name of a given variable.  Explanation and examples below.

<?php
 
function vname(&$var, $scope=false, $prefix='unique', $suffix='value')
  {
    if(
$scope) $vals = $scope;
    else     
$vals = $GLOBALS;
   
$old = $var;
   
$var = $new = $prefix.rand().$suffix;
   
$vname = FALSE;
    foreach(
$vals as $key => $val) {
      if(
$val === $new) $vname = $key;
    }
   
$var = $old;
    return
$vname;
  }
?>

Explanation:

The problem with figuring out what value is what key in that variables scope is that several variables might have the same value.  To remedy this, the variable is passed by reference and its value is then modified to a random value to make sure there will be a unique match.  Then we loop through the scope the variable is contained in and when there is a match of our modified value, we can grab the correct key.

Examples:

1.  Use of a variable contained in the global scope (default):
<?php
  $my_global_variable
= "My global string.";
  echo
vname($my_global_variable); // Outputs:  my_global_variable
?>

2.  Use of a local variable:
<?php
 
function my_local_func()
  {
   
$my_local_variable = "My local string.";
    return
vname($my_local_variable, get_defined_vars());
  }
  echo
my_local_func(); // Outputs: my_local_variable
?>

3.  Use of an object property:
<?php
 
class myclass
 
{
    public function
__constructor()
    {
     
$this->my_object_property = "My object property  string.";
    }
  }
 
$obj = new myclass;
  echo
vname($obj->my_object_property, $obj); // Outputs: my_object_property
?>
jospape at hotmail dot com
05-Feb-2005 07:45
$id = 2;
$cube_2 = "Test";

echo ${cube_.$id};

// will output: Test
ringo78 at xs4all dot nl
14-Jan-2005 08:27
<?
// I am beginning to like curly braces.
// I hope this helps for you work with them
$filename0="k";
$filename1="kl";
$filename2="klm";
 
$i=0;
for (
$varname = sprintf("filename%d",$i);   isset  ( ${$varname} ) ;   $varname = sprintf("filename%d", $i)  )  {
    echo
"${$varname} <br>";
   
$varname = sprintf("filename%d",$i);
   
$i++;
}
?>
Carel Solomon
07-Jan-2005 11:02
You can also construct a variable name by concatenating two different variables, such as:

<?

$arg
= "foo";
$val = "bar";

//${$arg$val} = "in valid";     // Invalid
${$arg . $val} = "working";

echo
$foobar;     // "working";
//echo $arg$val;         // Invalid
//echo ${$arg$val};     // Invalid
echo ${$arg . $val};    // "working"

?>

Carel
raja shahed at christine nothdurfter dot com
25-May-2004 06:58
<?php
error_reporting
(E_ALL);

$name = "Christine_Nothdurfter";
// not Christine Nothdurfter
// you are not allowed to leave a space inside a variable name ;)
$$name = "'s students of Tyrolean language ";

print
" $name{$$name}<br>";
print 
"$name$Christine_Nothdurfter";
// same
?>
webmaster at surrealwebs dot com
09-Mar-2004 08:31
OK how about a practicle use for this:

You have a session variable such as:
$_SESSION["foo"] = "bar"
and you want to reference it to change it alot throughout the program instaed of typing the whole thing over and over just type this:

$sess =& $_SESSION
$sess['foo'] = bar;

echo $sess['foo'] // returns bar
echo $_SESSION["foo"] // also returns bar
just saves alot of time in the long run

also try $get = $HTTP_GET_VARS
or $post = $HTTP_POST_VARS
webmaster at daersys dot net
20-Jan-2004 04:15
In reference to "remco at clickbizz dot nl"'s note I would like to add that you don't necessarily have to escape the dollar-sign before a variable if you want to output it's name.

You can use single quotes instead of double quotes, too.

For instance:

<?php
$var
= "test";

echo
"$var"; // Will output the string "test"

echo "\$var"; // Will output the string "$var"

echo '$var'; // Will do the exact same thing as the previous line
?>

Why?
Well, the reason for this is that the PHP Parser will not attempt to parse strings encapsulated in single quotes (as opposed to strings within double quotes) and therefore outputs exactly what it's being fed with :)

To output the value of a variable within a single-quote-encapsulated string you'll have to use something along the lines of the following code:

<?php
$var
= 'test';
/*
Using single quotes here seeing as I don't need the parser to actually parse the content of this variable but merely treat it as an ordinary string
*/

echo '$var = "' . $var . '"';
/*
Will output:
$var = "test"
*/
?>

HTH
- Daerion
unleaded at nospam dot unleadedonline dot net
15-Jan-2003 02:37
References are great if you want to point to a variable which you don't quite know the value yet ;)

eg:

$error_msg = &$messages['login_error']; // Create a reference

$messages['login_error'] = 'test'; // Then later on set the referenced value

echo $error_msg; // echo the 'referenced value'

The output will be:

test

定義済みの変数> <型の相互変換
Last updated: Fri, 18 Jul 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites