Php切换不更新变量

时间:2017-04-06 07:29:27

标签: php variables scope switch-statement

我有一个变量create_row(Initial)->create_row(Initial,[1]). create_row([First|Rest],Current) -> io:format("rest size: ~w ~n",[Rest]), create_row(Rest,lists:append(Current,[First+lists:nth(1, Rest)])); create_row([_|Rest],Current) when length(Rest)==0 -> lists:append(Current,[1]). ,它包含在$someVar中,并且应该根据不同的情况更改它的值。问题是$test没有在switch语句中更新。这是我的代码:

$someVar

这始终输出空<?php $someVar = ''; $test = '<div class="test">This is ' . $someVar . '</div>'; $param = 1; switch ($param) { case ($param == 1): $someVar = 'some text'; echo $test; break; }; ?> 并回显$someVar而不是This is。我猜这是一个范围问题所以任何帮助表示感谢,谢谢。

2 个答案:

答案 0 :(得分:4)

您在$test为空的那一刻定义了$someVar

$someVar = '';
$test = '<div class="test">This is ' . $someVar . '</div>';

将其更改为:

<?php
    $someVar = '';
    $test = '<div class="test">This is ' . $someVar . '</div>';
    $param = 1;
    switch ($param) {
        case ($param == 1):
            $someVar = 'some text';
            echo $test;
            break;
    };
?>

此:

<?php

$someVar = '';
$param = 1;
switch ($param)
{
    case 1:
        $someVar = 'some text';
        break;
};
$test = '<div class="test">This is ' . $someVar . '</div>';
echo $test;
?>

答案 1 :(得分:2)

如果您想更新$ test变量数据,那么您必须更新$ test变量,如下所示 -

<?php

$someVar = '';
$param = 1;
switch ($param)
{
     case 1:
        $someVar = 'some text';
        $test = '<div class="test">This is ' . $someVar . '</div>';
        break;
        case 2:
        $someVar = 'some text another';
        $test = '<div class="test">This is ' . $someVar . '</div>';
        break;
};
echo $test;
?>