установить максимальное количество элементов, которые вы можете сделать в функции - PullRequest
0 голосов
/ 16 февраля 2012

Как я могу сказать в / с последующей функцией (см. Ниже), что вы можете сделать максимум 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 ]

3 голосов
/ 16 февраля 2012

Используйте переменную статического счетчика:

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

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

См. Это в действии .

2 голосов
/ 16 февраля 2012

Если вы не слишком озабочены подделкой 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>
0 голосов
/ 17 февраля 2012

Большое спасибо за помощь !! Я сделал это следующим образом:

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;
} 

}

...