Konstruktionsplan
1 month ago
484
12
General

Crazy ✨Closure

Posted 1 month ago by Konstruktionsplan

Hello Friends! 👋🏻

According to the task definition I should build an anonymous function that adds "10" to the passed number.

I did not manage to do this myself, but had to look into the solution. I have listed it below. But I don't understand it completely, so I have some questions.

❓Warum don't I see 4 somewhere when I try to give $x the number 3?

❓Was exactly does this output mean?

❓Laut the test case this code works, only I don't understand why.

Thanks for the help!

Code:

function adds_n($n) {
	return function ($x) use ($n) {
      return $x + $n;
    };
}

print_r(adds_n(3));

Output:

Closure Object
(
    [static] => Array
        (
            [n] => 3
        )

    [parameter] => Array
        (
            [$x] => <required>
        )

)

Testcase:

public function testAdd() 
{
  public function testAdd() {
  $adds1 = adds_n(1);
  $this->assertEquals($adds1(3), 4);
 }
}

Please sign in or create an account to participate in this conversation.