0

I have the following code:

$mh = curl_multi_init();
$requests = array();

addSentimentHandle ( 'Hello', $requests );
addSentimentHandle ( 'Hello :)', $requests );

function addSentimentHandle($tweet, $requests) {
    $url = makeURLForAPICall($tweet);
    array_push($requests, curl_init ($url));
    print_r($requests);
}

I would expect the $requests array to contain two elements, however this is the output:

Array ( [0] => Resource id #8 ) Array ( [0] => Resource id #9 )

Why are 2 arrays are being created instead of the second item being pushed into the same array?

2
  • 7
    I believe you're pushing to a local instance inside addSentimentHandle(), have you tried passing the array by reference? function addSentimentHandle($tweet, &$requests) {} Commented Feb 5, 2015 at 18:15
  • Silly, silly me. Thank you, it works fine now. Commented Feb 5, 2015 at 18:25

1 Answer 1

2

I think that your problem is that you want to use $requests as a global variable. In your code it's not. You should pass it as a reference:

$mh = curl_multi_init();
$requests = array();

addSentimentHandle ( 'Hello', $requests );
addSentimentHandle ( 'Hello :)', $requests );

function addSentimentHandle($tweet, &$requests) {
    $url = makeURLForAPICall($tweet);
    array_push($requests, curl_init ($url));
    print_r($requests);
}

note the '&' as a prefix for $requests in function declaration. Then php wont used it as a local variable in this function.

I recommend to you to use php as an object oriented language.

class myAwesomeTweeterClass{
 protected $_requests;

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

 public function addSentimentHandle($tweet) {
    $url = makeURLForAPICall($tweet);
    array_push($this->_requests, curl_init ($url));
 }
 public function getRequests(){
    return $this->_requests;
 }
}
$mh = curl_multi_init();
$obj = new myAwesomeTweeterClass();
$obj->addSentimentHandle ( 'Hello');
$obj->addSentimentHandle ( 'Hello :)');
print_r($obj->getRequests());
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.