Home » Php » php – How to access an argument of the "parent" function?

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&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!");

Answer:

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.

Answer:

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();
}

Answer:

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!");
?>