CakeFest 2024: The Official CakePHP Conference

基本的な事

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

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

注意: ここで言うところの文字とはa-z、A-Z、128から255まで (0x80-0xff)のバイトを意味します。

注意: $this は特別な変数であり、ここに代入することはできません。 PHP 7.1.0 より前のバージョンでは、 (可変変数 を使った) 間接的な代入 が可能でした。

ヒント

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

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

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

$4site = 'not yet'; // 無効:数字で始まっている。
$_4site = 'not yet'; // 有効:アンダースコアで始まっている。
$tayte = 'mansikka'; // 有効:'a' はアスキーコード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 では変数を初期化する必要はありませんが、そのようにするのはとてもよいことです。 初期化されていない変数の値は、状況に応じたその型のデフォルト値 - boolean なら false、integer や float ならゼロ、 文字列 (echo で使う場合など) なら空の文字列、配列なら空の配列となります。

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

<?php
// 設定も参照もされていない (使用中のコンテキストではない) 変数は NULL となります
var_dump($unset_var);

// boolean として使用すると、出力は 'false' となります (この構文の詳細は三項演算子を参照ください)
echo $unset_bool ? "true\n" : "false\n";

// 文字列として使用すると、出力は 'string(3) "abc"' となります
$unset_str .= 'abc';
var_dump($unset_str);

// integer として使用すると、出力は 'int(25)' となります
$unset_int += 25; // 0 + 25 => 25
var_dump($unset_int);

// float として使用すると、出力は '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/ja/reserved.classes.php を参照ください)
// を作成すると、出力は object(stdClass)#1 (1) { ["foo"]=> string(3) "bar" } となります
$unset_obj->foo = 'bar';
var_dump($unset_obj);
?>

初期化されていない変数のデフォルト値に依存すると、そのファイルを include している別のファイルで同名の変数が使用されていた場合などに問題を起こします。 初期化されていない変数を使用すると、 E_WARNING (PHP 8.0.0 より前のバージョンでは E_NOTICE) レベルのエラーが発生します。 しかし、初期化されていない配列に要素を追加する場合はエラーにはなりません。 変数が初期化されているかどうかの判断には、isset() を使用します。

add a note

User Contributed Notes 2 notes

up
74
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
17
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
To Top