Hello eveyone:

I am learing PHP.

a) I am doing a exercise regarding global variable and local variable.

I want to print out the value of global variable inside a function. It's seems when I put function call after the function declaration the value will show, if I placed function call before the function declaration the value for global variable won't show.

b) the book I am using says if I attended to print a local variable outside of function, I will get an error message. my experienting result is that I didn't get a error message. Should I adjust some parameters in .ini file in order for this to happen? Please suggest which parameter(s) I shoul change in order to see the error messaage.

Please give me some advises on why this happned? Thanks!

<?php

displayCompanyName("IBM", "JPMorgans", "StarBucks");

$globalVar = "I am a global variable";

function displayCompanyName($company1, $company2,$company3)
{
  global $globalVar;
  $companyI;
  echo "$company1<br />";
  echo "$company2<br />";
  echo "$company3<br />";
  echo "$globalVar"; 
}

  //if place function call here value for $globalVar will show in browser

  echo $companyI; //** there is no error message in this case


?>

    The positioning of the function declaration doesn't matter. If you call the function before $globalVar is set, then $globalVar inside the function will have no value.

    You call adjust eror reporting on a script by script basis, which is often a good idea so your live scripts don't show errors. Put thow following inside the top opening PHP tag and you'll see all errors.

    error_reporting(E_ALL);

    Or if you'd prefer to change it in php.ini you need to do

    error_reporting = E_ALL

      Using "global" is most often a sign of bad code design. Avoid it. For one thing, it defeats a feature of good functions; in general you should not need to know the internals of a function in order to use it.

        Write a Reply...