duanke2503 2012-03-18 01:06
浏览 21
已采纳

PHP'fwrite'不会变量

I'm creating an IRC bot, and I wanted to store some functions in a different file. I reference the file in my main file with include() and it works, but when I try to give fwrite() a variable like so:

$data ="THIS IS DATA
";
fwrite($sock, $data);

It throws this error:

PHP Warning: feof() expects parameter 1 to be resource, null given in /home/kinz/Desktop/Eve/Eve.php on line 18

PHP Warning: fgets() expects parameter 1 to be resource, null given in /home/kinz/Desktop/Eve/Eve.php on

But when I put:

fwrite($sock, "THIS IS DATA
");

It works perfectly fine. Here is my full code:

function connect_s ($serv, $port, $nick) { $sock = fsockopen($serv, $port); fwrite($sock, "USER $nick $nick $nick :$nick
"); fwrite($socket, "NICK $nick
"); }
function write_d ($data) { fwrite($sock, $data); }
function join_c ($chan) { write_d("JOIN $chan
"); }
function get_in ($in) { for ($i = 3; $i <= count($in); $i++) { $out .= " $in[$i]"; } return trim("$out
"); }
function change_n ($nick) { write_d("NICK $nick
"); } ?>

I want to know why I can't use a variable as the second parameter in fwrite. Any help is greatly appreciated

  • 写回答

2条回答 默认 最新

  • duankao4489 2012-03-18 01:12
    关注

    Each new function has it's own scope for the variables. You've defined $sock in one function but it's not defined in the other functions. You need to do one of 3 things:

    1. Return $sock and pass it to any subsequent functions
    2. have global $sock; at the beginning of each of your functions
    3. write this all in an object class, and assign and use $this->sock as opposed to $sock

    3 would be the "best" solution, 1 would be how to accomplish this in a functional context, and 2 is probably the easiest but using globals in this way is the last resort.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000