Home > Net >  changing variable value outside a function inside a class
changing variable value outside a function inside a class

Time:04-16

how can i make it change the count value. the RollingCurlX thing is a multithreading class for php which only let you process response through a function and i dont know how you should handle it. please help me


class MyClass extends RollingCurlX {
  
  public function someFunc() {
    
    $url = 'https://example.com/';
    $count = 0;
    
    function callback_functn($response, $url, $request_info, $user_data, $time) {
      if ($response['c'] == 'd') {
        $count  ;
      }
    }
    
    $RCX = new RollingCurlX(10);
    for ($i=0; $i < 100; $i  ) {
      $post_data = ['a' => 'b'];
      $RCX->addRequest($url, $post_data, 'callback_functn');
    }
    $RCX->execute();
    
    echo $count;
    
  }
  
}

$c = new MyClass();
$c->someFunc();

CodePudding user response:

Use the use() declaration to give the function access to an external variable. Make it a reference with & so assignments to the variable inside the function will affect the outer variable.

function callback_functn($response, $url, $request_info, $user_data, $time) use (&$count) {
  if ($response['c'] == 'd') {
    $count  ;
  }
}

CodePudding user response:

Try it

public function someFunc() {

   $url = 'https://example.com/';
   $count = 0;

   $callbackFunction = static function ($response, $url, $request_info, $user_data, $time) use (&$count) {
      if ($response['c'] == 'd') {
         $count  ;
      }
   };

   $RCX = new RollingCurlX(10);

   for ($i = 0; $i < 100; $i  ) {
       $post_data = ['a' => 'b'];
       $RCX->addRequest($url, $post_data, $callbackFunction);
   }

   $RCX->execute();

   echo $count;
}
  •  Tags:  
  • php
  • Related