2016-01-13 41 views
-2

如果我使用fopen()外run方法它的工作,但它不是在運行方式工作,如何在php中創建一個文件到線程的運行函數?

<?php 
    class Test extends Thread{ 
     public function run(){ 
      $h = fopen("xyz.txt", "w+"); 
      fclose($h); 
     } 
    } 
    $p = new Test(); 
      $p->start(); 
      $p->join(); 

    ?> 

我想創建start();功能呼叫xyz.txt文件。

+0

沒有'start()'函數。您可以使用['touch()'](http://php.net/touch)創建文件...'function start(){touch(「xyz.txt」); }' –

+0

我在構造函數中創建file.my.my問題解決了。謝謝 !瑞安 –

回答

0

對於使用pthreads.so的線程內部fopen沒有什麼特別之處。下面是一個例子:

<?php 

$test = new Test(); 

class Test 
{ 
    public function __construct() 
    { 
     // A test folder 
     $folder = "/home/jkon/www/test"; 

     // If you like to interact in other ways you could keep that as 
     // private property 
     $thread = new TestThread($this, $folder); 
     $thread->start(); 
    } 

    public function getThreadMessage($code,$msg) 
    { 
     echo "CODE:".$code ." MSG:".$msg; 
    } 
} 


class TestThread extends Thread 
{ 
    private $folder; 

    /** 
    * @var Test 
    */ 
    private $test; 

    private $filename = "test.txt"; 
    private $txt = "THIS IS A TEST"; 

    public function __construct(Test $test,$folder) 
    { 
     $this->test = $test; 
     $this->folder = $folder; 
    } 

    public function run() 
    { 
     $resource = fopen($this->folder."/".$this->filename, 'w'); 
     if(!$resource) 
     { 
      $this->test->getThreadMessage(1001, "file open failed"); 
     } 
     else 
     { 
      $writeBytes = fwrite($resource, $this->txt); 
      $closed = fclose($resource); 
      if(!$closed) 
      { 
       $this->test->getThreadMessage(1002, "file close failed"); 
      } 
      else 
      { 
       $this->test->getThreadMessage(1002 
       , "file write successfully ".$writeBytes."bytes "); 
      } 
     } 
    } 
} 
?> 
相關問題