[PHP-users 28303] Re: セッション情報の更新条件

Atsushi SHICHI ats7 @ a.email.ne.jp
2006年 2月 2日 (木) 11:08:11 JST


しち です。

At Mon, 30 Jan 2006 13:21:59 +0900,
HOTTA Michihide <hotta @ net-newbie.com> wrote:

> ちなみに 
> $_SESSION = array(...)
> のように、代入時に変数を介さなければうまくいくようです。
> これはバグ?それとも仕様?

関連のありそうなバグレポートがありました。

http://bugs.php.net/bug.php?id=36239
| [1 Feb 9:18am CET] derick @ php.net
| 
| Sorry, but your problem does not imply a bug in PHP itself.  For a
| list of more appropriate places to ask for help using PHP, please
| visit http://www.php.net/support.php as this bug system is not the
| appropriate forum for asking support questions.  Due to the volume
| of reports we can not explain in detail here why your report is not
| a bug.  The support channels will be able to provide an explanation
| for you.
| 
| Thank you for your interest in PHP.
| 
| This is actually correct behavior. The $_SESSION array is special, and
| now you\'re overwriting it removing its special capabilities.

> リファレンスとかそのへんのからみかなぁとは思うんですが、どなたか
> この理由をわかりやすく説明していただけないでしょうか?

私も知りたいです。
以下のように each() を使うと期待どおりに動作して

<?php
session_start();
$remain = array('idx1', 'idx2', 'idx3');    //  残したいもの
reset($_SESSION);
while (list($key, $value) = each($_SESSION)) {
    if (!in_array($key, $remain)) {
        unset($_SESSION[$key]);             //  remain以外を未定義に
    }
}
print_r($_SESSION);
?>

foreach を使うと期待どおりに動作しない、というのがマニュアルにある
以下の注意書きを読んでも理解できません。ソースを読むしかないのかも
しれませんね。

http://jp.php.net/manual/ja/control-structures.foreach.php
| 注意: 配列がリファレンスでない限り、foreachは、指定した配列自体に
| 対してではなく、そのコピーに対して処理を行います。このため、each()
| 文のように配列のポインタ位置が変更されることはなく、返される配列要
| 素への変更は、元の配列には反映されません。しかし、元の配列の内部ポ
| インタは、配列の処理に伴い前に進められます。foreachループが完了した
| 時点で、配列の内部ポインタは、配列の最後を指すことになります。

--
Atsushi SHICHI
0x7E72D5FA / 72CD F89C 9840 2422 48D5  F04A CE97 8697 7E72 D5FA


PHP-users メーリングリストの案内