功能错误中的功能

时间:2014-02-11 10:27:52

标签: php function date

function Sign1(){
    $check = array(
        '23-03-2014' => 'saturday 22 may',
        '17-05-2014' => 'friday 16 may'
    );
    Dateoption();
}
function Sign2(){
    $check = array(
        '10-02-2014' => 'monday 10 feb',
        '15-02-2014' => 'friday 15 feb',
        '14-03-2014' => 'friday 14 march'
    );
    Dateoption();
}
function Dateoption(){
    $now = time();
    $result = array();
    foreach($check as $date => $text) {
        if($now  <= strtotime($date)) {
            $result[] = $text;
        }
    }
    $html = '';
    foreach($result as $v) {
        $html .= '<option>'.$v.'</option>';
    }
    return $html;
}
$Content= '
<div class="content">
    I am signing up for the following date:<br />
    <select name="date[0]">
        '. Sign1() .'
    </select>
    <select>
        '. Sign2() .'
    </select>
</div>
';
echo $Content;

为什么这不起作用?这是错误的@ foreach($ check as $ date =&gt; $ text){但是我必须改变才能让它工作。我这样做所以我只需要输入一次该函数,而不是将它粘贴到任何地方。

1 个答案:

答案 0 :(得分:1)

这与变量范围有关。 Dateoption无法看到$ check变量。 php documentation将其描述为:However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope.

您需要将$ check作为参数传递给Dateoption方法。

function Sign1(){
    $check = array(
        '23-03-2014' => 'saturday 22 may',
        '17-05-2014' => 'friday 16 may'
    );
    return Dateoption($check);
}
function Sign2(){
    $check = array(
        '10-02-2014' => 'monday 10 feb',
        '15-02-2014' => 'friday 15 feb',
        '14-03-2014' => 'friday 14 march'
    );
    return Dateoption($check);
}
function Dateoption($check){
    $now = time();
    $result = array();
    foreach($check as $date => $text) {
        if($now  <= strtotime($date)) {
            $result[] = $text;
        }
    }
    $html = '';
    foreach($result as $v) {
        $html .= '<option>'.$v.'</option>';
    }
    return $html;
}
$Content= '
<div class="content">
    I am signing up for the following date:<br />
    <select name="date[0]">
        '. Sign1() .'
    </select>
    <select>
        '. Sign2() .'
    </select>
</div>
';
echo $Content;