HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Functions

The real power of PHP comes from its functions. A function is a block of statements that can be used repeatedly in a program. It will not execute automatically when a page loads; it must be called by the script.


1. Creating a User-Defined Function

A user-defined function declaration starts with the word function, followed by the name you give to that function.

<?php
    function writeMsg() {
        echo "Hello, welcome to RedoHub!";
    }
?>

2. Calling a Function

To call the function, just write its name followed by parentheses (). You can call the same function multiple times wherever needed.

<?php
    function writeMsg() {
        echo "Hello, welcome to RedoHub!";
    }

    writeMsg(); // Call the function
?>
Naming Rules: Function names must start with a letter or underscore (not a number). Unlike variables, function names are not case-sensitive, but it is standard practice to name them consistently (e.g., writeMessage()).

Why Use Functions?

  • Reusability: Write the code once and use it in many different places.
  • Maintainability: If you need to fix a bug, you only have to change it in one place (inside the function).
  • Organization: Functions help break a large, complex script into smaller, manageable pieces.
Pro Tip: Give your functions descriptive names that describe what they do (e.g., calculateTotal() instead of func1()).

Key Points to Remember

  • A function is a reusable block of code.
  • Functions only run when they are called.
  • Always use the function keyword followed by a unique name.
  • Function names are not case-sensitive (but consistency matters).
  • Functions make your code cleaner and easier to debug.