设置您可以在功能中创建的项目的最大值

时间:2012-02-16 13:49:36

标签: php function

如何在/中使用以下(见下文)功能,您可以制作最多3项?如果您将生成三个以上的项目,该功能将停止并收到警告?

function addSection() {
global $compid;
    $sectionOb = new Item();
    $sectionOb->i_id_pk = $sectionOb->newId();
    $sectionOb->i_mod_comp_id_fk = $compid;
    $sectionOb->c_titel = '';
    $sectionOb->c_content = '';
    $sectionOb->i_sort = $sectionOb->newSort($compid);
    $sectionOb->insert();
}

if($action == 'add') {  
    addSection();
}


<a href="<?php echo $_SERVER['REQUEST_URI'] ?>&amp;action=add" />new section</a>

3 个答案:

答案 0 :(得分:3)

使用静态计数器变量:

function limited() {
    static $invocationcount = 0;
    ++$invocationcount;

    if($invocationcount <= 3) {
        echo "You have called this function $invocationcount times.";
    }
    else {
        echo "Stop doing that!";
    }
}

<强> See it in action

答案 1 :(得分:2)

如果您不太关心URL欺骗,我会在URL中添加一个计数器变量,传递给addSection()方法,如下所示:

function addSection($count) {
    if ($count >= 3) { return $count; }
    global $compid;
    $sectionOb = new Item();
    $sectionOb->i_id_pk = $sectionOb->newId();
    $sectionOb->i_mod_comp_id_fk = $compid;
    $sectionOb->c_titel = '';
    $sectionOb->c_content = '';
    $sectionOb->i_sort = $sectionOb->newSort($compid);
    $sectionOb->insert();

    // Return incremented count
    return $count + 1;
}

// Retrieve the last count from the URL
$count = isset($_GET['count']) ? intval($_GET['count']) : 0;

// Increment the count if the action is add and the addSection method suceedes
if($action == 'add') {  
    $count = addSection($count); 
}

// Add count to the URL so we know what it is
<a href="<?php echo $_SERVER['REQUEST_URI'] ?>&action=add&count=<?php echo $count; ?>" />new section</a>

答案 2 :(得分:0)

非常感谢您的帮助!! 我按照以下方式进行操作:

function limit() {
global $compid;
$i = 0;
++$i;
$a_all = page1::page2Id($compid);
$i = sizeof($a_all);

if($i <= 2) { 
    $sectionOb = section();
    $sectionOb->i_id_pk = $sectionOb->newId();
    $sectionOb->i_mod_comp_id_fk = $compid;
    $sectionOb->c_titel = '';
    $sectionOb->c_content = '';
    $sectionOb->i_sort = $sectionOb->newSort($compid);
    $sectionOb->insert();
    return true;
} 
else { 
return false;
} 

}