About Lesson
PHP Functions (Defining and Calling)
Functions are blocks of reusable code. You define them once and can use them multiple times in your program. They make code more organized, readable, and efficient.
Syntax of a Function:
function functionName() {
// Code to be executed
}
function
→ a keyword used to define a function.functionName
→ the name you give your function (it should begin with a letter or an underscore).{ }
→ this is where the code that executes when the function is called.
Example 1. Simple Function
PHP
<?php
function sayHello() {
echo "Hello, welcome to PHP Functions!<br>";
}
// Calling the function
sayHello();
sayHello();
?>
Explanation:
- In this example, we defined the sayHello() function just once, but we called it twice.
- Output:
- Hello, welcome to PHP Functions!
Hello, welcome to PHP Functions!
- Hello, welcome to PHP Functions!
Example 2. Function with HTML Integration
PHP
<!DOCTYPE html>
<html>
<head>
<title>PHP Function Example</title>
</head>
<body>
<?php
function greetUser() {
echo "<h2 style='color:green;'>Hello, Student! Learn PHP Functions here.</h2>";
}
// Calling the function inside HTML
greetUser();
?>
</body>
</html>
Explanation:
- A green heading will appear:
- Output:
- Hello, Student! Learn PHP Functions here.
Example 3. Using Multiple Functions
PHP
<?php
function heading() {
echo "<h1>Welcome to My Website</h1>";
}
function footer() {
echo "<footer>© 2025 My Website</footer>";
}
// Calling the functions
heading();
echo "<p>This is the body of the page.</p>";
footer();
?>
Explanation:
- This illustrates how you can break down code into different sections by using functions.
- Output:
- Welcome to My Website
- This is the body of the page.
- © 2025 My Website