Today I saw a post on php.net, that I’m quoting here:
$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";
$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a
$$$$$$a; //Returns Hello
$$$$$$$a; //Returns World
Since PHP inherits its syntax from C++, doesn’t the dollar sign remind you of pointers?
string bar = "a";
string *foo = &bar;
string **world = &foo;
string ***hello = &world;
string ****a = &hello;
Just like pointers, when you define $a = 'var' and $var = 'test' and then you do $$a you are using the value of $a to point to $var which is kinda what happens with C++ pointers just with strings instead of memory addresses.
So can the dollar sign in PHP be related to C++ pointers?
Stop. This line of thinking will get you nothing but pain and suffering. Perl, LPC, Lua, Pike, Ada 95, Java, PHP, D, C99, C#, and Falcon are all derived from C++ as well, for some definition of "derived", and I can guarantee you they act nothing like C++ and are certainly not used like C++ either. The similarities are superficial in nature, and their semantics are totally different.
In the case you provided above, it’s more similar to languages like Javascript in the sense that you can resolve and dereference a variable name given only a string. In C++ knowing just the name of the variable doesn’t allow you to dereference the variable. What you need is its memory address (hence the
&operator). That’s the key difference.I think the most salient point of misunderstanding here is this part of your question:
This isn’t explanation doesn’t capture the entire picture with regards to pointers. I assume you’re talking about things like these:
PHP:
C++:
The big difference between the two is that C++’s
acontains a memory address for thevarvariable, not a string containing the name of the variablevar.It’s more like reflection than anything else, which C++ certainly does not have as standard, and thus cannot just simply dereference a variable given only a string name.
From the PHP documentation for variable variables:
If C++ had that kind of functionality, it would be more like this:
This is very different from simple pointer dereferencing, as pointers do not hold strings, they hold memory addresses. Even though you shouldn’t be using pointers in your code anyway except in very specific circumstances.