0

What I am trying to achieve is this:

$x = 5;
$b = function ($x) {
    echo 'This should be 5 :' . $x;
};
function a($fn){
    echo 'In a ';
    $fn();
}
a($b);

That when you run this code, we get

In a

This should be 5 :5

What we get instead is

Warning: Missing argument 1 for {closure}(), called in writecodeonline.com/php on line 10 and defined on line 3 This should be 5

I don't want to redefine the argument I already defined

What I don't want neither is hide the $x. I don't want to change its visibility.

Is there a way for this?

0

2 Answers 2

3

Read the docs: you can use the use expression for it:

$x = 5;

$b = function () use ($x) {
    echo 'This is x: ' . $x . "\n";
};

$b();

$c = function ($fn) {
    echo 'In c: ';
    $fn();
};

$c($b);
$x = 10;
$c($b);

Output:

This is x: 5
In c: This is x: 5
In c: This is x: 5

Note that despite the change of $x later the assigned value does not get changed. You can achieve that if you pass the variable by reference:

$x = 5;

$b = function () use (&$x) { // << Note the difference here
    echo 'This is x: ' . $x . "\n";
};

$b();

$c = function ($fn) {
    echo 'In c: ';
    $fn();
};

$c($b);
$x = 10;
$c($b);

Output:

This is x: 5
In c: This is x: 5
In c: This is x: 10
Sign up to request clarification or add additional context in comments.

Comments

1

Read about variable scope, $x cannot be automagically visible inside function a() unless you pass the argument into function a()

$x = 5;

$b = function ($x) {
    echo 'This should be 5 :' . $x;
};

function a($fn, $value) {
    echo 'In a ';
    $fn($value);
}

a($b, $x);

2 Comments

this would certainly work, but you make the microing of $value through your whole application to get it to work.
microing? If you need to pass an argument to your function $b(), then it must be passed to $b() at the point where $b() is called, not simply where it is defined. You're calling $b() from within function a(), so the argument must exist within the scope of a()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.