Create custom class extending stream in yii2

How to create a custom class that does not extend the component 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 works fine in a clean php application
And Pthread is installed!

+5
source share
2 answers

Something extensions means that the Something class is searched in the current namespace. \Something means the class was looking in the root namespace. See the basics of namespaces .

You do not have the common\components\Thread class in your common\components namespace. In your case use class AsyncOperation extends \Thread {

+6
source

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

I noticed that you have markup in your stream and you are using a web framework.

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

Recent releases of pthreads forbid execution inside the web server , you will need to do something different if you want to use PHP7 and pthreads, which will soon become the only supported way to use pthreads.

+1
source

Source: https://habr.com/ru/post/1232077/


All Articles