0

I got a class constructor which kicks off a curl_multi and goes about downloading certain number of files and takes a few seconds to complete. Will the object instance be created only after the constructor is done with the downloads?

class Downloader {
  public function __construct($download_links_array,...) {
     $handle = new curl_multi_init();
     ...
  }
}

$downloader = new Downloader( array($download_links) );
$downloader->get_item(10); // Will this be too early to call?

So the question is will the instance get created before invoking get_item() or it will the control only be returned after the instance (ie, all the downloads are completed) is created?

Thanks!

user2727704
  • 625
  • 1
  • 10
  • 21

1 Answers1

0

It depends. How do you download your files? synchronously or not? If you do it synchronously, then your call of the function which executes the download will not return until the files are downloaded. Otherwise, the function will return immediately and your files will be downloaded in the background (usually you need to supply a callback function that handles the event of finishing the downloads while working asynchronously).

Moreover, an object is not considered ready as long as the constructor has not finished its work. That means, that the new call won't return until the object is ready, i.e. the constructor is finished.

Combining the two sections above teaches us that if the downloading is done synchronously, the object will be ready only after downloads are finished, thus the call of get_item will be executed only after all of the downloads are finished. However, if you download your files asynchronously, then the object will be ready regardless of when your downloads are finished, and the call for get_item may be executed even before your downloads are finished.

You can read this answer which might bring you better understanding on the difference between the two (as they discuss a very simple example of executing a query which might take a long time instead of downloading files).

Note: Constructors really do not need to perform such tasks.

Community
  • 1
  • 1
Idan Yadgar
  • 974
  • 1
  • 6
  • 16