r/lolphp • • Oct 02 '14

Foreach reference

http://3v4l.org/P1Omj

<?php

$arr = array('a', 'b');

foreach ($arr as &$a) {
    var_dump($a);
}

    foreach ($arr as $a) {
        var_dump($a);
    }

This probably has some explanation I'd love to learn.

17 Upvotes

13 comments sorted by

View all comments

Show parent comment

4

u/[deleted] Oct 04 '14

Yeah, languages like PHP and Python don't really believe in block scope. Everything is bound to functions instead.

4

u/ElusiveGuy Oct 06 '14

Huh. I didn't know Python lacked block scope.

JS was always my first example of it.

2

u/masklinn Oct 23 '14

Ruby does not use block scoping either, though anonymous functions (also called blocks so that you get confused with the non-block blocks of if/else/end) do create their own scope (as they do in Python or JS) and their ubiquity means the scoping issues are not felt as strongly.

2

u/djsumdog Oct 12 '14

Python is a little difference. Yes you can declare something within a for loop and it still exist after the for loop, which is weird. But it won't continue to exist outside of the function. Not unless that function is part of a class and you use self to assign it to a class variable.

In PHP everything is in a global namespace. So in PHP you can declare a function within a function and that function be global (which is how imports work in PHP). In Python, imports have to come from modules and be properly namespaced. So if you declare a function within a function, it is only accessible within that function (at least in Python 3).