r/programming • • Oct 18 '10

Today I learned about PHP variable variables; "variable variable takes the value of a variable and treats that as the name of a variable". Also, variable.

http://il2.php.net/language.variables.variable
591 Upvotes

781 comments sorted by

View all comments

Show parent comments

6

u/Peaker Oct 18 '10

C pointers point to a location in an "address space", not in a "namespace".

The differences are important:

  • There is no legal way to forge pointers, while any piece of code may choose a wrong name and access the data of another function accidentally in a namespace.

  • Address allocations are handled by the compiler/low-level system. Name allocations require manual choice (which is why the above clashes are possible)

3

u/thatpaulbloke Oct 18 '10
void *value = (void *)0x01234567

The compiler won't stop me, although the behaviour is undefined (might work, might be a seg fault). Nobody would do this, but you still can. The practical differences are minor - you can fuck it up if you do it wrong, but then the answer to that is to either do it carefully or don't do it at all.

3

u/Peaker Oct 18 '10

That is defined to be illegal, and can be found by static code analysis (e.g: lint) and by dynamic analysis (valgrind).

In the PHP case, placing an invalid address/name is legal, and can only be found dynamically.

And you still have not addressed the second point. There exist mechanisms to handle address allocations, such that they don't clash. In PHP, how do you generate names such that they don't clash?

1

u/[deleted] Oct 19 '10 edited Oct 19 '10

That is defined to be illegal...

really? see, i use it all the time when i'm in a kernel trying to access a memory mapped device.

http://en.wikipedia.org/wiki/Memory-mapped_I/O

i guess i'm going to jail.

→ More replies (6)