7

For example I have the following code:

function a($param)
{
  function b()
  {
    echo $param;
  }
  b();
}
a("Hello World!");

That throws an E_NOTICE error because $param is of course undefined (in b()).

I cannot pass $param to b() because b() should be a callback function of preg_replace_callback(). So I had the idea to save $param in $GLOBALS.

Is there any better solution?

ComFreek
  • 29,044
  • 18
  • 104
  • 156

4 Answers4

12

If you are using PHP 5.3, you could use anonymous function with use keyword instead:

<?php
function a($param)
{
  $b = function() use ($param)
  {
    echo $param;
  };

  $b();
}
a("Hello World!");
Ondrej Slinták
  • 31,386
  • 20
  • 94
  • 126
1

BTW, since this was tagged functional-programming: in most functional programming languages, you would just refer to param, and it would be in scope, no problem. It's called lexical scoping, or sometimes block scoping.

It's typically languages without explicit variable declarations (eg "assign to define") that make it complicated and/or broken. And Java, which makes you mark such variables final.

Ryan Culpepper
  • 10,495
  • 4
  • 31
  • 30
0

I'd suggest using objects here.

Class a {
    private $param;
    private static $instance;

    public function __construct($param){
        $this->param = $param;
        self::$instance = $this;
    }

    public function getParam(){
        return $this->param;
    }

    public static function getInstance(){
        return self::$instance;
    }

}

function b(){
    echo a::getParam();
}
Travis Weston
  • 903
  • 6
  • 24
0

I suggest the use of each function lonely, and call the second function from the first function passing parameters.

It do your code more clear because each function do a single set of operations.

<?php
function a($param)
{
  b($param);
}
function b($param)
{
    echo $param;
}
a("Hello World!");
?>
Memochipan
  • 3,405
  • 5
  • 35
  • 60
  • But I want to use b() as a callback function of preg_replace_callback. So with your solution I have to make $param globally available. – ComFreek Jul 16 '11 at 15:30
  • Maybe these links help you: [http://stackoverflow.com/questions/48947/how-do-i-implement-a-callback-in-php] and [http://stackoverflow.com/questions/4016264/php-callback-functions] – Memochipan Jul 16 '11 at 15:41
  • Maybe you must consider other alternatives since the solution above by Ondrej Slinták only works in PHP 5.3. In PHP 5.2 it returns parse error in line 4. – Memochipan Jul 16 '11 at 15:50
  • Yes, but the script I build only minimizes my own scripts (so 5.3.1). But how would look an alternative with preg_replace_callback? Can you give me an example? – ComFreek Jul 16 '11 at 16:02
  • Before PHP 5.3 create_function() was used. http://www.php.net/manual/en/function.create-function.php – Memochipan Jul 16 '11 at 17:16