Home > Blockchain >  Does writing $x; mean anything in PHP?
Does writing $x; mean anything in PHP?

Time:11-01

To create a variable x with the value 12345 in PHP, we do the following:

<?php
    $x = 12345;
?>

But let's say that we wrote $x; without assigning it a value:

<?php
    $x;
?>

Does the above code causes anything to happen, or does PHP treat the above $x; as non-existent? for example is the above code effectively the same as the following empty code?:

<?php

?>

CodePudding user response:

<?php
    $x;
?>

These line of code mean you just initialize a variable name called x. but you doesn't assign value. But it will use some memory.

You can check use of memory:

<?php
$x;
echo memory_get_usage($x);
?> 

Your Empty CODE :

<?php

?>

These line of code means you just initialize PHP script. But inside there is nothing actually. But it also use some memory.

You can check use of memory:

<?php
echo memory_get_usage();
?>

Hope you understand the difference.

CodePudding user response:

If you look at what are the defined variables in the following script...

print_r(get_defined_vars());
$x;
print_r(get_defined_vars());
$x = 1;
print_r(get_defined_vars());

You can see that just using $x; doesn't define the variable, it only shows up after assigning it a value. So effectively this is the same as doing nothing.

Also checking the opcodes being generated...

With $x=1; - phpdbg -p* a.php

function name: (null)
L1-4 {main}() /home/nigel/a.php - 0x7f2f36c8e000   3 ops
 L3    #0     EXT_STMT                                                                              
 L3    #1     ASSIGN                  $x                   1                                        
 L4    #2     RETURN<-1>              1                                                             

with $x; - phpdbg -p* a.php

function name: (null)
L1-4 {main}() /home/nigel/a.php - 0x7f5898079050   2 ops
 L4    #0     EXT_STMT                                                                              
 L4    #1     RETURN<-1>              1  

So it looks as though no opcode is generated.

  •  Tags:  
  • php
  • Related