-1

I have a function that writes it into a file.

public function write($type = "error", $mensaje = "") { 
    $this->file = fopen($this->filePath.$this->fileName, "a+"); 

    if ($this->file == null) { 
        trigger_error("Error: No file", E_USER_ERROR); 
    } else { 
        fwrite($this->file, $type." ".$mensaje."\n");
    } 
}

I need to call this function from another php file say index.php

function test() {
    write("testing done");
    echo "done";
}

I want the write function to be called from index.php asynchronously so the current execution doesn't stop or block if the write fails.

7
  • You might perhaps find this of interest / use. stackoverflow.com/questions/124462/asynchronous-php-calls?rq=1 Commented Sep 17, 2015 at 9:47
  • Write the above function in a class and call the class to the index.php Commented Sep 17, 2015 at 9:49
  • @SobinAugustine that could block the execution Commented Sep 17, 2015 at 9:50
  • Unfortunately, PHP does not support multithreading so there is not really a way to do this easily. You could build something using cron or something, but that would be too broad to explain here. That being said, your write function doesn't look so bad to just call it in the main thread. Commented Sep 17, 2015 at 9:54
  • maybe use pthreads, check this: stackoverflow.com/a/27364939/1855357 Commented Sep 17, 2015 at 9:55

1 Answer 1

0

with phptreads ( http://php.net/manual/en/intro.pthreads.php ), something like

class writerThread extends Thread {
public function __construct($type="error",$message=''){
  $this->type=$type;
$this->message=$message;
}

public function run(){
   file_put_contents($filename,$this->type.$this->message);
}
}

$writer=new WriterThread("testing done");
$writer->start();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.