Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the Variable in inner function PHP?

How to access the variable in inner function of outer function variable?

I want to access $arr variable in the inner function.

<?php

function outer() {

    $arr = array();

    function inner($val) {

        global $arr;

        if($val > 0) {
            array_push($arr,$val);
        }
    }

    inner(0);
    inner(10);
    inner(20);

    print_r($arr);

}

outer();

codepad link

like image 882
kpmDev Avatar asked Nov 15 '25 16:11

kpmDev


1 Answers

This kind of "inner function" does not do what you probably expect. The global(!) function inner() will be defined upon calling outer(). This also means, calling outer() twice results in a "cannot redefine inner()" error.

As @hindmost pointed out, you need closures, functions that can get access to variables of the current scope. Also, while normal functions cannot have a local scope, closures can, because they are stored as variables.

Your code with Closures:

function outer() {

    $arr = array();

    $inner = function($val) use (&$arr) {
        if($val > 0) {
            array_push($arr,$val);
        }
    }

    $inner(0);
    $inner(10);
    $inner(20);

    print_r($arr);

}

outer();
like image 127
Fabian Schmengler Avatar answered Nov 17 '25 09:11

Fabian Schmengler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!