1

I have used PHP for a very long time, but not really used callbacks very much until quite recently. In the following code, the callback (the example is QueryPath, in case you're wondering, but it could be anything that accepts a callback) will add some link to an array:

// parse any product links out of the html
$aProducts = array();
qp( $html, 'a' )->each(function($index, $element){
    global $aProducts;

    $link = qp($element)->attr('href');

    $pregMatch = preg_match('@(.*)-p-(.*)\.html@i', $link, $matches);


   if( $pregMatch ) {
        $product_id = (int)$matches[2];

                if( !in_array($product_id, $aProducts) ) {
            $aProducts[] = $product_id;
        }
    }


});

    // print out our product array
    print_r( $aProducts );

What's the alternative to using global $aProducts (if there is one)?

Eva
  • 4,859
  • 3
  • 20
  • 26

2 Answers2

4

use use:

qp( $html, 'a' )->each(function($index, $element) use(&$aProducts) {

Note the &. This is needed, for otherwise you would be using a copy of the array. You can also use multiply values, just list them separated with a ,. E.g: use(&$aProducts, $someObj, &$someInt)

PHP.net: http://www.php.net/manual/en/language.namespaces.importing.php

Eva
  • 4,859
  • 3
  • 20
  • 26
Yoshi
  • 54,081
  • 14
  • 89
  • 103
  • It's not necessary to use & for objects though right? (I guess for copy functionality you do `clone $someObj`?) – Eva Feb 02 '13 at 13:55
  • No, for objects you don't need the &. It works the same, like when you would pass values to a function. – Yoshi Feb 02 '13 at 13:56
  • ;) I also didn't find a good link directly, I'll post it when I have one. For now maybe the general page on [Anonymous functions](http://php.net/manual/functions.anonymous.php) will help? – Yoshi Feb 02 '13 at 14:02
  • If I understand the man page correctly, was this not possible before PHP 5.3, or was `use` in use before PHP 5.3, but just for anonymous functions? – Eva Feb 02 '13 at 14:21
0

I Recommend you To Don't Use global variable, instead put your code on a Class and Use $this instead global variable. it must Work

mohammad mohsenipur
  • 3,218
  • 2
  • 17
  • 22