Functions play a crucial role in organizing and reusing code in any programming language. In this lesson, we will explore creating and using functions in PHP, as well as understanding the concept of variable scope.

Creating Functions

To create a function in PHP, you need to use the function keyword followed by the function name and a pair of parentheses. The function body should be enclosed in curly braces.

function helloWorld() {
  echo "Hello, World!";
}

Calling Functions

To call (or invoke) a function, simply use the function name followed by parentheses.

helloWorld(); // Output: Hello, World!

Function Parameters

You can define parameters for your function by specifying them inside the parentheses. When calling the function, you need to provide arguments for these parameters.

function greet($name) {
  echo "Hello, $name!";
}

greet("John"); // Output: Hello, John!

Default Parameter Values

You can provide default values for function parameters by assigning a value with the equal sign (=) in the parameter definition.

function greet($name = "World") {
  echo "Hello, $name!";
}

greet(); // Output: Hello, World!
greet("Jane"); // Output: Hello, Jane!

Variable Scope

In PHP, variables have different scopes based on where they are defined. Variables defined inside a function have local scope, which means they can only be accessed within that function. Variables defined outside of any function have global scope and can be accessed from anywhere in the script.

$globalVar = "I'm a global variable.";

function showLocalVar() {
  $localVar = "I'm a local variable.";
  echo $localVar; // Output: I'm a local variable.
}

showLocalVar();
echo $globalVar; // Output: I'm a global variable.

To use a global variable inside a function, you need to use the global keyword.

$globalVar = "I'm a global variable.";

function showGlobalVar() {
  global $globalVar;
  echo $globalVar; // Output: I'm a global variable.
}

showGlobalVar();

Actionable Work:

Practice creating and using functions in PHP by completing the following exercises: