# 控制结构

Zephir实现了一组简化的控制结构，这些结构用类似的语言表示，如C、PHP等。

## 条件

### If 语句

`if` statements evaluate an expression, executing the following block if the evaluation is `true`. 括号是必需的。 一个`如果`可以有一个可选的`else`子句, 而且多个`if`/`else`构造可以放在一起

``````if false {
echo "false?";
} else {
if true {
echo "true!";
} else {
echo "neither true nor false";
}
}
``````

`elseif`也有条件

``````if a > 100 {
echo "to big";
} elseif a < 0 {
echo "to small";
} elseif a == 50 {
echo "perfect!";
} else {
echo "ok";
}
``````

``````if a < 0 { return -1; } else { if a > 0 { return 1; } }
``````

### Switch 语句

``````switch count(items) {

case 1:
case 3:
echo "odd items";
break;

case 2:
case 4:
echo "even items";
break;

default:
echo "unknown items";
}
``````

## Loops

### While 语句

`while` denotes a loop that iterates as long as its given condition evaluates as `true`:

``````let counter = 5;
while counter {
let counter -= 1;
}
``````

### Loop 语句

``````let n = 40;
loop {
let n -= 2;
if n % 5 == 0 { break; }
echo x, "\n";
}
``````

### For 语句

`for` 是一种控制结构, 允许遍历数组或字符串:

``````for item in ["a", "b", "c", "d"] {
echo item, "\n";
}
``````

``````let items = ["a": 1, "b": 2, "c": 3, "d": 4];

for key, value in items {
echo key, " ", value, "\n";
}
``````

``````let items = [1, 2, 3, 4, 5];

for value in reverse items {
echo value, "\n";
}
`</pre>

` for </ 0>循环可用于遍历字符串变量：</p>

string language = "zephir"; char ch;

for ch in language {
echo "[", ch ,"]";
}
`</pre>

```zephir
string language = "zephir"; char ch;

for ch in reverse language {
echo "[", ch ,"]";
}
```

```zephir
for i in range(1, 10) {
echo i, "\n";
}
```

for key, _ in data {
echo key, "\n";
}
`</pre>

### Break 语句
`break` 结束当前 `while`、`for` 或 `loop` 语句的执行:

```zephir
for item in ["a", "b", "c", "d"] {
if item == "c" {
break; // exit the for
}
echo item, "\n";
}
```

### Continue 语句

```zephir
let a = 5;
while a > 0 {
let a--;
if a == 3 {
continue;
}
echo a, "\n";
}
```

## Require
` require </ 0>语句动态地包含和执行指定的PHP文件。 请注意，Zend Engine将Zephir包含的文件解释为普通的PHP文件。 require` does not allow Zephir code to include other Zephir files at runtime.

```zephir
if file_exists(path) {
require path;
}
```

## Let
`let` 语句用于可变变量、属性和数组。 变量默认是不可变的，并且该指令使它们在语句的作用域内是可变的：

```zephir
let name = "Tony";           // simple variable
let this->name = "Tony";     // object property
let data["name"] = "Tony";   // array index
let self::_name = "Tony";    // static property
```

```zephir
let number++;           // increment simple variable
let number--;           // decrement simple variable
let this->number++;     // increment object property
let this->number--;     // decrement object property
```

let price = 1.00, realPrice = price, status = false;
`</pre>
``````