【发布时间】:2015-11-19 06:50:06
【问题描述】:
我正在使用 PHP 中的 for-loop 和 CLI。我遇到了递减运算符(--)的问题。下面是我的代码,
<?php
$handle = fopen("php://stdin","r");
$str = fgets($handle);
for($i=$str; $i>0; $i--){
var_dump($i);
}
对于任何大于 0 的数字,它都会进入无限循环。下面是输出,
john@doe:/var/www/html/rank$ php 1.php
3
string(2) "3
"
string(2) "3
"
string(2) "3
"
string(2) "3
"
string(2) "3
"
string(2) "3
"
但如果我将强制转换 cli 参数显式键入 int,它会起作用,
<?php
$handle = fopen("php://stdin","r");
$str = (int)fgets($handle);
for($i=$str; $i>0; $i--){
var_dump($i);
}
输出
john@doe:/var/www/html/rank$ php 1.php
3
int(3)
int(2)
int(1)
john@doe:/var/www/html/rank$
是我做错了什么还是类型杂耍不适用于减量运算符(故意)?因为它似乎可以与下面的增量运算符(++)一起使用
<?php
$handle = fopen("php://stdin","r");
$str = fgets($handle);
for($i="1"; $i<=$str; $i++){
var_dump($i);
}
输出
john@doe:/var/www/html/rank$ php 1.php
3
string(1) "1"
int(2)
int(3)
john@doe:/var/www/html/rank$
【问题讨论】:
标签: php type-conversion decrement