Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly does PHP achieve 'dynamic' variables?

I was marvelled when I tested the following code today:

$star = "Aquarius";
$star = 11;

While debugging, I observed that $star simply changes from string type to integer type. I was amazed by this functionality. In C++ for instance, this is just impossible, but in c# I considered the var variable but it's not the same.

For instance you can't do:

var dynamic = "Hello";
dynamic = 3;

I began to wonder what exactly happens at the point when I basically say $star = 11. My guess is that $star is simply reinitialized since it's being directly assigned to (but this seems weird since the interpreter already knows that a variable $star has been declared earlier). Can anyone help with some clear or official source-backed explanation?

Thanks.

like image 393
rtuner Avatar asked Sep 22 '12 22:09

rtuner


1 Answers

In C/C++ the type is defined at compile time because of the kinds of optimization that can occur based on it.

In C# the compiler infers the type based on the context and in the compilers brain it substitutes the var keyword for the type. This is why you can not change the type after the compiler made the initial inference.

In scripting languages like PHP a variable is an entry into a Hash Map (Associative Array, a Symbol Table). This defines the namespace (and scope). The actual value part is a generic object type that stores both the value and the type.

like image 61
Darryl Miles Avatar answered Oct 25 '22 01:10

Darryl Miles