我有这段代码:
$file = '/path/to/file.txt';
if (($fd = fopen($file, "a") !== false)) {
fwrite($fd, 'message to be written' . "\n");
fclose($fd);
}
为什么会收到以下警告?
fwrite(): supplied argument is not a valid stream resource
fclose(): supplied argument is not a valid stream resource
答案 0 :(得分:7)
您的if语句错误。尝试
if (($fd = fopen($file, "a")) !== false) {
因为你的一个就像
$fd = fopen($file, "a") !== false
答案 1 :(得分:2)
因为您有一个括号错误。代码应为:
if (($fd = fopen($file, "a")) !== false) {
当前代码将$fd
设置为将fopen
返回值与false
进行比较的结果,false
也是fopen
(假设if ($fd = false) {
成功)。实际上你有
var_dump
这是不言自明的,也是可测试的(if
)。
故事的寓意:不要为{{1}}条件中的变量赋值。这不是1980年,你不是用C编程。只要说不,让核心可读;它会爱你的。