PHP打开2 TCP套接字



当我在php中打开2个不同的套接字时,我首先获得不同的资源id,但在打开下一个套接字后,获得相等的资源id。下面是连接到三个不同套接字的结果

# ./test.php

127.0.0.1:26379/132458106d92e8f7b127.0.0.1:26379 -资源id #8127.0.0.1:6380/320458106d92e906e127.0.0.1:6380 -资源id #9127.0.0.1:6381/102858106d92e9106127.0.0.1:6381 -资源id #10资源id #10Array([timed_out] =>[blocked] => 1(eof) =>[stream_type] => tcp_socket/ssl[mode] => r+[unread_bytes] => 0[seekable] =>)

资源id #10Array([timed_out] =>[blocked] => 1(eof) =>[stream_type] => tcp_socket/ssl[mode] => r+[unread_bytes] => 0[seekable] =>)

资源id #10Array([timed_out] =>[blocked] => 1(eof) =>[stream_type] => tcp_socket/ssl[mode] => r+[unread_bytes] => 0[seekable] =>)

我在下面使用代码:

class RedisClient    
function __construct ($arr = array ())
    {
        if (count($arr) === 0) return FALSE;
        self::$host = $arr[0];
        self::$port = $arr[1];
        self::$persistent = '/' . uniqid(rand(100,10000));
        self::$fp =
            stream_socket_client('tcp://'.self::$host . ':' .
                                 self::$port .
                                 self::$persistent, $errno, $errstr, self::$connect_timeout, self::$flags);
        echo self::$host,':',self::$port,self::$persistent,PHP_EOL;
        if (!self::$fp) {
            echo "$errstr ($errno)" . PHP_EOL;
            return FALSE;
        }
        echo self::$host,':',self::$port,' - ';
        print_r(self::$fp);
        echo PHP_EOL;
        if (!stream_set_timeout(self::$fp, self::$timeout)) return FALSE;
    }
function getMeta ()
    {
        print_r (self::$fp);
        print_r (stream_get_meta_data(self::$fp));
        return;
    }
$c=new RedisClient(array('127.0.0.1',26379));
$m=new RedisClient(array('127.0.0.1',6380));
$s=new RedisClient(array('127.0.0.1',6381));
$c->getMeta();
echo PHP_EOL;
$m->getMeta();
echo PHP_EOL;
$s->getMeta();
echo PHP_EOL;
exit;

有人知道,为什么所有的套接字连接后,所有的资源id,是相同的?有什么不同呢?

您使用了self::$fp(静态变量),您需要在类中使用$this来按对象获取不同的变量

"self::$var = 1;" -为class创建一个变量(没有对象)

"$this->var = 1;" -在对象

中创建属性

例如:

class Test {
   protected $a = 1;
   protected static $b = 1;
   public function incA()
   {
       $this->a++;
   }
   public static function incB()
   {
       self::$b++;
   }
   public function getA()
   {
       return $this->a;
   }
   public static function getB()
   {
       return self::$b;
   }
}
$test = new Test();
$test->incA();
$test->incA();
var_dump($test->getA());
var_dump(Test::getB()); // or $test::getB();
Test::incB();
$test2 = new Test();
var_dump($test2->getA());
var_dump($test2::getB());
var_dump($test::getB());
var_dump(Test::getB());

点击这里阅读更多

相关内容

  • 没有找到相关文章

最新更新