【问题标题】:Function in a Function Errors函数错误中的函数
【发布时间】:2014-02-11 10:27:52
【问题描述】:
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 => $text) { 出错了,但我必须改变什么才能让它工作。我正在这样做所以我只需键入一次函数,而不是到处复制粘贴。

【问题讨论】:

  • 你以“And again”开头,这是一种奇怪的提问方式。另外,它应该做什么,它实际上做了什么,为什么 Sign1 中的日期与它们的描述无关?
  • 请为您的问题添加标签。尤其是所涉及的语言。

标签: php function date


【解决方案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;

【讨论】:

  • 是的,我们现在的方式是正确的,但是选择部分中没有任何显示?你知道吗?
  • Sign1 和 Sign2 也需要返回 Dateoption 的输出。我已经更新了我的答案。
  • 这样啊!谢谢你!这对我帮助很大! (是的,我知道我有时有点傻,但这就是我问的原因,我从中学到了很多!)
猜你喜欢
  • 1970-01-01
  • 2019-11-01
  • 2020-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-23
  • 2021-04-04
  • 2016-04-07
相关资源
最近更新 更多