PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Алтернативен синтаксис за контролни структури> <else
Last updated: Fri, 27 Jun 2008

view this page in

elseif

elseif, както подсказва и името й, е комбинация от if и else. Също както else, тя разширява конструкцията if така, че да изпълни различна инструкция, в случай че първоначалният израз if се е изчислил на FALSE. За разлика от else обаче тя ще изпълни този алтернативен израз само ако условният израз elseif се изчислява на TRUE. Например, следният код ще изведе a е по-голямо от b, a е равно на b или a е по-малко от b:

<?php
if ($a $b) {
    echo 
"a е по-голямо от b";
} elseif (
$a == $b) {
    echo 
"a е равно на b";
} else {
    echo 
"a е по-малко от b";
}
?>

В рамките на една конструкция if може да има много elseif-ове. Първият израз elseif (ако има такъв), който се изчисли на TRUE ще бъде изпълнен. В PHP можете също да напишете и 'else if' (с две думи) и поведението му ще бъде идентично на 'elseif' (с една дума). Синтактичното значение е малко по-различно (ако сте запознати със C, тук е налице същото поведение), но последният ред е този, който и в двата случая ще има абсолютно същото поведение.

Конструкцията elseif се изпълнява само ако предшестващият израз if и всички предшестващи изрази elseif се изчислят на FALSE и текущият израз elseif се е изчислил на TRUE.



add a note add a note User Contributed Notes
elseif
31-Jan-2007 11:54
There is no good way to interpret the dangling else.  One must pick a way and apply rules based on that. 

Since there is no endif before an else, there is no easy way for PHP to know what you mean.
Vladimir Kornea
27-Dec-2006 06:59
The parser doesn't handle mixing alternative if syntaxes as reasonably as possible.

The following is illegal (as it should be):

<?
if($a):
    echo $a;
else {
    echo $c;
}
?>

This is also illegal (as it should be):

<?
if($a) {
    echo $a;
}
else:
    echo $c;
endif;
?>

But since the two alternative if syntaxes are not interchangeable, it's reasonable to expect that the parser wouldn't try matching else statements using one style to if statement using the alternative style. In other words, one would expect that this would work:

<?
if($a):
    echo $a;
    if($b) {
      echo $b;
    }
else:
    echo $c;
endif;
?>

Instead of concluding that the else statement was intended to match the if($b) statement (and erroring out), the parser could match the else statement to the if($a) statement, which shares its syntax.

While it's understandable that the PHP developers don't consider this a bug, or don't consider it a bug worth their time, jsimlo was right to point out that mixing alternative if syntaxes might lead to unexpected results.

 
show source | credits | sitemap | contact | advertising | mirror sites