Skip to main content
  1. Tech
  2. Gadgets & Tech
  3. Tech Gear

Using functions in a PHP program (part 4)

See also

Using functions in a PHP program (part 4)

As mentioned in the last article, Using functions in a PHP program (part 3), we will continue with a global variable discussion and demonstration. As discussed previously in Using a variable in a PHP program, the same rules apply. Please refer to the article for a refresher.

A global variable can be accessed in any part of the program. It is essential that you explicitly declare a variable global in the function in which it is to be modified, by placing the keyword global in front of the variable that is intended to be global as shown below:

global $name;

NOTE: As demonstrated in the previous programs, we used notepad a plain text editor. The PHP programs are stored on our web server, "C:\Wampserver\www." Please note the stored web server location.

Now let us create the PHP program, please follow the steps outlined below:

  1. Select and click "Start."
  2. Select and click "All Programs."
  3. Select and click "Accessories."
  4. Select and click "Notepad."
  5. Type the PHP code exactly as shown below.

<html>

<head>

<title>Global Variable</title>

</head>

<body><h1>Global variable</h1>

<h3>Demonstrates use of global variable<h3>

<?php

function format_name()

{

global $name;

$first_name = "Jane";

$last_name = "Singer";

$name = $last_name.", ".$first_name;

}

format_name();

print "$name";

?>

</body>

</html>

  1. Once you have type the entire program, Select "File," "Save As," and then go to the webroot of your server. For example, C:\Wampserver\www. Type Filename, globalvariable.php," and then Select "Save."

In the next article of the Using functions in a PHP program (part 5); we will discuss passing values to a function.

Advertisement