Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create custom class that extend thread in yii2

how create custom class not extend components class ?

class :

 namespace common\components;

 class AsyncOperation extends Thread {

  public function __construct($arg) {
    $this->arg = $arg;
}

public function run() {
    if ($this->arg) {
        $sleep = mt_rand(1, 10);
        printf('%s: %s  -start -sleeps %d' . "<br />", date("g:i:sa"),     $this->arg, $sleep);
        sleep($sleep);
        printf('%s: %s  -finish' . "<br />", date("g:i:sa"), $this->arg);
      }
   }

}

yii2 controller:

   public function actionTest() {
  // Create a array
    $stack = array();

//Iniciate Miltiple Thread
    foreach (range("A", "D") as $i) {
        $stack[] = new AsyncOperation($i);
    }

    // Start The Threads
    foreach ($stack as $t) {
        $t->start();
    }
}

error:

 PHP Fatal Error – yii\base\ErrorException
Class 'common\components\Thread' not found

This class is working perfect in pure php app
And Pthread is installed!

like image 595
Mohsen Avatar asked Sep 23 '15 08:09

Mohsen


2 Answers

Extends Something means that class Something searched in current namespace. \Something means that class searched in root namespace. See basics of namespaces.

You don't have class common\components\Thread in your common\components namespace. In your case use class AsyncOperation extends \Thread {

like image 135
Onedev_Link Avatar answered Nov 17 '22 08:11

Onedev_Link


Someone already gave you the answer you were looking for ... however ...

I notice you have markup in your thread, and are using a web framework.

I'm going to assume you are creating threads at the frontend of your web application, inside a web server: This is a terrible idea.

The latest releases of pthreads prohibit execution inside a web server, you are going to need to do things differently if you want to use PHP7 and pthreads, which is soon to be the only supported way to use pthreads.

like image 32
Joe Watkins Avatar answered Nov 17 '22 07:11

Joe Watkins