Search code examples
phpsyntaxclosuresscoping

Is it possible to inherit a parent scope member property and assign it to a inner variable in the "use" statement?


The following works (also with objects etc.):

$b = new stdClass();

$b->a = "foo";
$b->b = "bar";

$example = function () use ($b) {
    echo $b->b;
};
$example();

Is there some syntax trick for passing some object property/array member and assigning it to a new variable at the same time without defining this variable in the outer scope?

This pseudo-code example should demonstrate what I mean:

$b = new stdClass();

$b->a = "foo";
$b->b = "bar";

$example = function () use ($b->b as $prop) {
    echo $prop;
};
$example();

Solution

  • Why not just define it as a parameter and be done with it? What you are trying to do is exactly what functions do normally.

    E.g. and following exactly the use case you present in your question:

    $example = function ($prop) {
        echo $prop;
    };
    
    $example($b->b);
    

    Of course, if you want to modify the variable, you just need to declare it as passing by reference:

    $anotherExample = function (&$prop) {
        echo $prop;
    };
    

    use doesn't do what you want to do, nor it makes much sense that it would. Simply passing parameters to a function, which is in the basic nature of functions, solves this "issue".