Skip to content
Advertisement

What is the scope of a PHP function defined within a PHP anonymous function?

Question

If I do this:

$checkName = function ($value) use ($min, $max)  {
    function lengthTest($string, $min, $max)
    {
        $length = mb_strlen($string, 'UTF-8');
        return ($length >= $min) && ($length <= $max);
    }
};

1) Is it legal PHP? And …

2) Is the function lengthTest() in the global namespace, or limited to just the $checkName Closure object? Would it be a private member, then?

3) Can lengthTest() be refereced as a callback method for filter_var_array() like this?

$filterInstructionsArray [
    'fName'   => ['filter' => FILTER_CALLBACK],
    'flags'   => FILTER_REQUIRE_SCALAR,
    'options' => [$checkName, 'lengthTest']]
];

4) Can lengthTest be referenced as a callback function for filter_var_array() like this?

$filterInstructionsArray [
    'fName'   => ['filter' => FILTER_CALLBACK],
    'flags'   => FILTER_REQUIRE_SCALAR,
    'options' => 'lengthTest']
];

References

The PHP Manual says the following about user defined functions:

Any valid PHP code may appear inside a function, even other functions and class definitions. … All functions and classes in PHP have the global scope – they can be called outside a function even if they were defined inside and vice versa.

The PHP Manual says the following about anonymous functions:

Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses. Closures can also be used as the values of variables; PHP automatically converts such expressions into instances of the Closure internal class. Assigning a closure to a variable uses the same syntax as any other assignment, including the trailing semicolon:

Thank you for taking the time to read, think about, and respond to my question. I appreciate it very much.

Advertisement

Answer

Cracks knuckles

Technically the syntax is “correct” (it won’t generate a fatal error) but the semantics of PHP render it effectively meaningless in its current form. Let’s look at a few things first, namely how PHP handles the assignment of named functions to variables:

php > echo shell_exec("php -v");
PHP 5.4.16 (cli) (built: Oct 30 2018 19:30:51)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies

php > function speak($arg) {echo "{$arg}n";}
php > function give($arg) {return $arg;}
php > $speak = speak(4);
4
php > $give = give(4);
php > var_dump($speak);
NULL
php > var_dump($give);
int(4)

The function itself is executed upon assignment and its return value (NULL or otherwise) is assigned to the variable. Since we’re only assigning the return value of a function’s execution, trying to use this variable as a function name has no use:

php > $speak(4);
php > $give(4);
php >

Let’s contrast this to the assignment of an anonymous function (a.k.a. a ‘Closure’):

php > $min = 1; $max = 6;
php > $checkName = function ($value) use ($min, $max) {
php {   echo "value: {$value}n";
php {   echo "min: {$min}n";
php {   echo "max: {$max}n";
php { };
php > var_dump($checkName);
object(Closure)#1 (2) {
  ["static"]=>
  array(2) {
    ["min"]=>
    int(1)
    ["max"]=>
    int(6)
  }
  ["parameter"]=>
  array(1) {
    ["$value"]=>
    string(10) "<required>"
  }
}

Unlike some other languages, a closure is represented in PHP by an actual Object. Variables inside the ‘use’ clause are imported at the time the Closure was created; function parameters (i.e. $value) have their values captured when the Closure is called (hence why we see it noted as a required parameter and not a static value). The semantics of references within Closures aren’t worth considering right now but if you want further reading, goat‘s answer to this question is a great start.

The major takeaway here is that the Closure’s assignment to $checkName did not execute the Closure itself. Instead, $checkName becomes a sort of “alias” we can use to reference this function by name:

php > $checkName("hello stackoverflow");
value: hello stackoverflow
min: 1
max: 6
php >

Given how loose PHP is about the number of function parameters passed, a zero-parameter execution returns expected results:

php > $checkName();
value:
min: 1
max: 6
php >

Now let’s take it another level deeper and define a function within a function:

php > function myOuterFunc($arg) {
php {   function myInnerFunc($arg){
php {     echo "{$arg}n";
php {   }
php { }
php > $myVal = myOuterFunc("Hello stackoverflow");
php > var_dump($myVal);
NULL
php >

By now this result should make sense. Functions do not execute unless explicitly called; just because we call myOuterFunc doesn’t mean we execute any function code defined inside of it. That’s not to say that we couldn’t:

php > function myOuterFunc($arg) {
php {   function myInnerFunc($arg){
php {     echo "{$arg}n";
php {   }
php {   myInnerFunc($arg);
php { }
php > $myVal = myOuterFunc("Hello stackoverflow");
Hello stackoverflow
php > var_dump($myVal);
NULL
php >

Which brings us back around to what is essentially your question: what about a named function inside of a Closure? Given what we’ve now discovered about function execution, we can generate a series of very predictable examples:

$min = 1; $max = 6;
$checkName = function ($value) use ($min, $max) {
  function question(){echo "How are youn";}
  echo "value: {$value}n";
  echo "min: {$min}n";
  echo "max: {$max}n";
};
php > $checkName("Hello stackoverflow");
value: Hello stackoverflow
min: 1
max: 6
php >

As expected, the named function’s code inside the Closure is not executed because we have not explicitly called it.

php > $min = 1; $max = 6;
php > $checkName = function ($value) use ($min, $max) {
php {   function question(){echo "How are youn";}
php {   echo "value: {$value}n";
php {   echo "min: {$min}n";
php {   echo "max: {$max}n";
php {   question();
php { };
php > $checkName("Hello stackoverflow");
value: Hello stackoverflow
min: 1
max: 6
How are you
php >

Explicitly calling the inner function works just fine, provided we define that function before we call it:

php > $min = 1; $max = 6;
php > $checkName = function ($value) use ($min, $max) {
php {   echo "value: {$value}n";
php {   echo "min: {$min}n";
php {   echo "max: {$max}n";
php {   question();
php {   function question(){echo "How are youn";}
php { };
php > $checkName("Hello stackoverflow");
value: Hello stackoverflow
min: 1
max: 6
php >

php > $min = 1; $max = 6;
php > $checkName = function ($value) use ($min, $max) {
php {   echo "value: {$value}n";
php {   echo "min: {$min}n";
php {   echo "max: {$max}n";
php {   function question(){echo "How are youn";}
php {   question();
php { };
php > $checkName("Hello stackoverflow");
value: Hello stackoverflow
min: 1
max: 6
How are you
php >

So to the point of your questions then:

  1. Yes it’s legal and what you’re attempting is possible but semantically meaningless in its current form.

  2. Any named functions inside the Closure definitely do not reside in the global namespace, they are within the scope of their defining Closure. FWIW, the term “members” typically refers to class variables (usually called “properties” in PHP). While Closures are an Object and let you duplicate the functionality of instance variables found within classes, they should not be confused or construed with classes in any way.

3/4) Not how you’re trying to use it, no. Nothing outside of the Closure has any concept of the functions inside; if in calling your Closure code, said code performs operations using the inner functions, then they will see the light of day. But there is no immediate way to reference those inner functions as if they were defined outside of the Closure’s scope.

In other words, the only way you’ll get those inner functions to execute is if a) that code is specifically executed by the Closure’s code and b) you execute said Closure code.

Hope this helps.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement