Understanding Local Variables in PHP: Usage and Best Practices

Rumman Ansari   Software Engineer   2024-07-18 09:16:06   5448  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

A variable declared in a function is considered local; that is, it can be referenced solely in that function. Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function ?

Example:



 
<?php
   $x = 4;
   
   function assignValue () { 
      $x = 0;
      print "\$x inside function is $x. <br />";
   }
   
   assignValue();
   print "\$x outside of function is $x. <br />";
?>


Output:

This will produce the following result -



$x inside function is 0.
$x outside of function is 4.