Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does PHP know what type of variables it uses (or does it)?

I haven't done much programing in many languages, but I know in C(++), you have to declare a variable type (int,char,etc).

In PHP you, of course, don't have to do that. You can start with $str = "something"; then later $str = array("something" => "smells"); and she is happy.

How does PHP compile? How does it know what the variable type is going to be? Does it even care?

This question has no relevance to anything I am doing. I am just curious.

EDIT.

I need to clarify this question a little bit.

In C, if I say:

int y;

It reserves x amount of bytes for y. If y overflows, bad news.

PHP doesn't have this nature (at least I don't think it does).

$i = "a number";
$i = 8;
$i = 1000000000000000000;

It's all the same to the language. How does it know how much to reserve? Or am I comparing Apples to Oranges? If I am going about this wrong, do you have any good topics that I can read to better understand?

like image 234
Jason Avatar asked Oct 28 '10 03:10

Jason


1 Answers

Since you have C experience, consider a PHP variable to be like the following:

typedef struct {
 int varType;
 void* data;
} variable_t;

when you create a new variable, it will create a variable_t, give it a type tag (lets say 1 for int, 2 for string), and store it in a list somewhere (by scope, reference by name). The actual contents will be stored in *data. When the variable is again accessed, the type can be determined from int varType, and the appropiate action taken on void* data, such as using it as an int or string.

Imagine that the PHP snippet:

 $data = 12;
 $data2 = $data + 1;
 $data = "Hello";

produces instructions like the following (pseudo-Cish):

Line 1:
variable_t* var = new_variable(TYPE_INT, data);
store_variable("data", var);

Line 2:
variable_t* var = get_variable("data2");
if (var->varType == TYPE_INT)
   int value = 1 + *(int*)var->data);
else
   error("Can't add non int");
var = new_variable(TYPE_INT, value);
store_variable("data2", var);

Line 3:
variable_t* var = get_variable("data");
if (var)
  destroy_variable(var);
// Do like line 1, but for TYPE_STRING

This type of augmented data works in bytecoded, compiled, or direct interpreted languages.

There are more details in regards to different virtual machine implementations (local allocation, heap allocation, register VMs, etc). If you actually want to understand how virtual machines work, the best reference is Lua. Very clean language, very clean bytecode, and very clean virtual machine. PHP is probably the last implementation you should look at.

like image 164
Yann Ramin Avatar answered Sep 20 '22 09:09

Yann Ramin