fwrite() 错误:提供的参数不是有效的流资源。为什么?
我有以下代码:
$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
I have this code:
$file = '/path/to/file.txt';
if (($fd = fopen($file, "a") !== false)) {
fwrite($fd, 'message to be written' . "\n");
fclose($fd);
}
Why do I get the following warnings?
fwrite(): supplied argument is not a valid stream resource
fclose(): supplied argument is not a valid stream resource
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的 if 语句是错误的。尝试一下
,因为你的就像
Your if statement is wrong. Try
Because yours one is like
因为你有一个括号错误。代码应为:
当前代码所做的是将
$fd
设置为将fopen
返回值与false
进行比较的结果,这也是false
(假设fopen
成功)。实际上,您已经拥有了不言自明且可测试的内容(使用
var_dump
)。故事的寓意:不要为
if
条件内的变量赋值。现在不是 1980 年,你也不是用 C 语言编程。只要说“不”并让核心可读即可;它会因此而爱你。Because you have a parenthesizing error. The code should read:
What the current code does is set
$fd
to the result of comparing thefopen
return value withfalse
, which is alsofalse
(assuming thefopen
succeeds). In effect you havewhich is self-explanatory and also testable (with
var_dump
).The moral of the story: Don't assign values to variables inside
if
conditions. This is not 1980, and you are not programming in C. Just say no and make the core readable; it will love you for it.