Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access an argument of the "parent" function?

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?

like image 674
ComFreek Avatar asked Jul 16 '11 15:07

ComFreek


2 Answers

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!");
like image 133
Ondrej Slinták Avatar answered Sep 19 '22 18:09

Ondrej Slinták


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.

like image 43
Ryan Culpepper Avatar answered Sep 22 '22 18:09

Ryan Culpepper