Friday, November 22, 2024

Top 8 Types of Functions in PHP You Must Know

PHP is a powerful server-side scripting language offering a wide range of functions to facilitate various tasks. Functions in PHP are blocks of code that execute only when called. They can accept data, parameters as input, process it, and return an output using 'return' or simply execute code within the function without returning a value. Such functions are called void functions. If you use a function that PHP has already written for you, such as 'is_numeric' and many others, these are called built-in functions. If a function is located within a class, it is called a method. Regardless of whether you are working with built-in functions, writing your own, or using advanced concepts like closures, understanding functions is crucial for efficient PHP programming. Functions in PHP are a powerful tool that enables modularity, code reuse, and flexibility. You should use them whenever it makes sense in your code, while also professionally creating your own.

Many years ago, if you asked us how many types of functions there are, we would have thought about the basic division and answered four:

a function that takes no parameters and returns a value

a function that takes parameters and does not return a value

a function that takes no parameters but returns a value

a function that takes no parameters and do not return a value

Today, PHP has proven us wrong. There are many more types of functions in the PHP programming language, and today we will list the top 8 that you will often use in your projects.

The student is thrilled with exploring the capabilities of functions in PHP

The student is thrilled with exploring the capabilities of functions in PHP

To make things much clearer for you regarding the numerous functions in PHP, let's dive straight into the practical part when it comes to functions. This is the easiest way to go through and explain even 8 types of functions in the PHP programming language. Unlike previous lessons in this PHP tutorial, today we'll expand our PHP coding by using a CSS file in addition to Bootstrap. You might wonder why use CSS when you're using Bootstrap. The reason is simple. There are things in HTML and PHP coding that you can't always style using Bootstrap alone. So, for larger projects, you'll often find that CSS styling is used in addition to Bootstrap. Nowadays, there are systems that don't allow the use of Bootstrap for security reasons, they only use CSS, while we've never seen a project that prohibited the use of CSS. That's why you should always learn and know how to use HTML and CSS together with PHP. Our HTML & CSS tutorial will make it easier for you to learn or simply refresh your memory, click here.

Then we'll learn how to pass data from one PHP page with an HTML form to another PHP page for further processing. Also, since there are multiple functions, we'll place them in a separate PHP file and teach you how to connect PHP files, so that you have the impression that separate functions in another PHP file are available as if they were in the same one. This PHP lesson might sound a bit complicated, but let us reassure you by coding everything together, writing simple code that you can definitely use in your projects.

Choose the Right Function for the Job: 8 Function Types for Better Code

Let’s first initiate your Apache Server by executing the following commands in your terminal.

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ cd /opt/lampp

manuel@manuel-virtual-machine:~$ ls

manuel@manuel-virtual-machine:/opt/lampp$ sudo ./manager-linux-x64.run

When the XAMPP manager window opens, start the Apache Web Server and open VisualStudio Code. Click on index.php, then in the code editor panel, modify the following part of the code.

<?php

    $title = 'PHP Tutorial';

    require_once 'includes/header.php'; 

?>

<h2 class="bg-primary text-light text-center py-3">Contents</h2>

<div class="container">

    <div>

        <h2><font color="seagreen">Lessons</font></h2>

        <ul>

        <li><a href="lessons/lesson01.php">

            Lesson 1. - The text printing and comments

        </a></li>

        <li><a href="lessons/lesson02.php">

            Lesson 2. - Variables and data types  

        </a></li>

        <li><a href="lessons/lesson03.php">

            Lesson 3. - Operators

        </a></li>

        <li><a href="lessons/lesson04.php">

            Lesson 4. - Conditional Statement if-else

        </a></li>

        <li><a href="lessons/lesson05.php">

            Lesson 5. - Conditional Statement switch-case

        </a></li>

        <li><a href="lessons/lesson06.php">

            Lesson 6. - The while Loop

        </a></li>

        <li><a href="lessons/lesson07.php">

            Lesson 7. - The do-while Loop

        </a></li>

        <li><a href="lessons/lesson08.php">

            Lesson 8. - The for Loop

        </a></li>

        <li><a href="lessons/lesson09.php">

            Lesson 9. - The foreach Loop

        </a></li>

        <li><a href="lessons/lesson10.php">

            Lesson 10. - The Arrays    

        </a></li>

        <li><a href="lessons/lesson11.php">

                Lesson 11. - 10 Key Strategies for Preventing Errors in PHP Programming

        </a></li>

        <li><a href="lessons/lesson12.php">

                Lesson 12. - Unlocking the Power of PHP Functions

            </a></li>

        </ul>

    </div>

</div>

<!-- footer -->

<?php require_once 'includes/footer.php'; ?>

Next, create a new folder and name it css. Inside it, create a file called my_style.css and enter the following code.

 /* call this css in header.php */

.form-group label span {

    color: red !important;

    font-size: 12px !important;  

} 

This code allows you to color the text in red within forms, specifically in labels when you have text between span tags. Open the header.php file in the includes folder and add the following line of code:

<link rel="stylesheet" href="../css/my_style.css">

Go to the lessons folder and create three new PHP files. Name them lesson12.php, lesson12b.php and my_functions.php. Open lesson12.php and enter the following code:

<?php

    // Sets the page title

    $title = 'Lesson 12';

    // Includes the header title

    require_once '../includes/header.php';

?>

<h2 class="bg-primary text-light text-center py-3">

    Unlocking the Power of PHP Functions

</h2>

<div class="container">

<h4>User Parameters</h4>

<form method="POST" action="lesson12b.php">

  <div class="form-group">

    <label for="fname">First Name:<span class="required"> *</span></label>

    <input type="text" name="fname" class="form-control" id="fname" placeholder="Enter first name" required>

  </div>

  <div class="form-group">

    <label for="lname">Last Name:<span class="required"> *</span></label>

    <input type="text" name="lname"  class="form-control" id="lname" placeholder="Enter last name" required>

  </div>

  <div class="form-group">

    <label for="city">City:<span class="required"> *</span></label>

    <input type="text" name="city"  class="form-control" id="city" placeholder="Enter city" required>

  </div>

  <div class="form-group">

    <label for="temperature">Temperature:<span class="required"> *</span></label>

    <input type="text" name="temperature" class="form-control" id="temperature" placeholder="Enter temperature" required>

  </div>

  <div>

    <br/>

    <button type="submit" class="btn btn-primary">Submit</button>

  </div>

</form>

</div>

<!-- footer -->

<?php require_once '../includes/footer.php'; ?>

When you run this page, the result will be similar to the following image depending on your entered data.

User Parameters Form

User Parameters Form

As you can see in the above code, we don't include any PHP code for error handling. We do that in the lesson12b.php file which is executed when the user clicks the Submit button. Before we start with the functions let's test the form. Write the following code:

<?php

    // Sets the page title

    $title = 'Lesson 12';

    // Includes the header title

    require_once '../includes/header.php';

    // Includes the file with functions

    require_once 'my_functions.php';

?>

<h2 class="bg-primary text-light text-center py-3">

    Unlocking the Power of PHP Functions

</h2>

<div class="container">

<h3>Types of Functions</h3>

<?php

    // Check if the data was sent via the POST method

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

        # Download data

        $fname = htmlspecialchars(trim($_POST['fname'] ?? ''));

        $lname = htmlspecialchars(trim($_POST['lname'] ?? ''));

        $city = htmlspecialchars(trim($_POST['city'] ?? ''));

        $temperature = htmlspecialchars(trim($_POST['temperature'] ?? ''));

        // Validation: We check if the fields are filled

        if (!empty($fname) && !empty($lname) && !empty($city) && !empty($temperature)

                && is_numeric($temperature)) {         

            // You can add calculations or save data to the database here

            // Display the results

            stars();

            echo "<div style='margin: 20px;'>";

            echo "<h4>Form Data Submitted Successfully!</h4>";

            echo "<p><strong>First Name:</strong> $fname</p>";

            echo "<p><strong>Last Name:</strong> $lname</p>";

            echo "<p><strong>City:</strong> $city</p>";

            echo "<p><strong>Temperature (Celsius):</strong> $temperature</p>";

            echo "</div>";          

        } else {

            // If some fields are not filled

            echo "<div style='margin: 20px; color: red;'>";

            echo "<h1>Error: All fields are required! Temperature must be a number!</h1>";

            echo "<a href='lesson12.php'>Go back to the form</a>";

            echo "</div>";

         }

    } else {

        // If the page is accessed without submitting the form

        echo "<div style='margin: 20px; color: red;'>";

        echo "<h1>No data submitted!</h1>";

        echo "<a href='lesson12.php'>Go back to the form</a>";

        echo "</div>";    

 }   

?> 

</div>

<!-- footer -->

<?php require_once '../includes/footer.php'; ?>

Run the form again, but this time instead of the value 10 for the temperature, put the value 10s, as if you accidentally made a mistake, and press the Submit button. Look at the image and see what you get as a result. This is a practical example of how errors are handled in PHP code, regardless of HTML or even JavaScript code validation, because they can be bypassed. PHP is the last line of defense.

The error message if you send another character for the temperature value instead of a number

The error message if you send another character for the temperature value instead of a number

While it's uncommon to find PHP functions in separate files nowadays, as classes are the preferred approach, we've opted for this method because we haven't covered classes yet. However, in the upcoming section on using functions in an object-oriented context, we'll demonstrate how simple PHP classes can be. Note that the file my_functions.php requires PHP tags to enclose your function definitions. Additionally, this file must be included in any other PHP file where you want to utilize these functions. Please add the following code to the beginning of lesson12b.php.

// Includes the file with functions

require_once 'my_functions.php';

Open the my_function.php file and enter the following code:

<?php

    // This is a function that does not take parameters or return a result

    function stars() {

        echo "<p>************************************************************</p>";

    }

    // This is a function that accepts parameters but does not return a result

    function title($title) {

        echo "<h4>" . $title . "</h4>";

    }

    // This is a function that takes parameters and returns a  result.

    function fahrenheit($celsius) {

        return $celsius * 9 / 5 + 32;

    }

?>

We've created three basic PHP functions: one for drawing a line of asterisks, another for generating HTML headings, and a third for converting Celsius to Fahrenheit. Let's use these functions in our lesson12.php file.

// Display the results

            stars();

            echo "<div style='margin: 20px;'>";

            echo "<h4>Form Data Submitted Successfully!</h4>";

            echo "<p><strong>First Name:</strong> $fname</p>";

            echo "<p><strong>Last Name:</strong> $lname</p>";

            echo "<p><strong>City:</strong> $city</p>";

            echo "<p><strong>Temperature (Celsius):</strong> $temperature</p>";

            echo "</div>";

            stars();

            // Built-in Function

            title("1. Built-in Function");

            echo "<p>date() - formats the date and time.</p>";

            echo "<p>Today is: " . date("Y-m-d") . "</p>";

            // User-defined Functions

            title("2. User-defined Functions");

            echo "<p>fahrenheit(celsius) - converts fahrenheit to celsius.</p>";

            echo "<p>" . $temperature . " Centigrade is equal to " . fahrenheit($temperature) . "</p>";


Run the project and see the result. It will look similar to the following image depending on the data you entered into the form.

 
Use of the first PHP functions in practice

Use of the first PHP functions in practice

The first type of functions in PHP is built-in functions. As you can see in the code, we didn't create the is_numeric function for the temperature value. We simply called it when we needed it. The second type of function is a custom function, which means functions created by the user. In this case, we created a custom function as an example that converts a value from Celsius to Fahrenheit, and we called it where needed. Open my_function.php and enter the PHP code for the following three functions.

// This is a recursive function

    function factorial($n) {

        if ($n <= 1) {

            return 1;

        }

        return $n * factorial($n - 1);

    }

    // This is an anonymous function

    $hello = function($name) {

        return "Hello, $name!";

    };

    // This is a closure

    function makeGreeting($honorifics) {

        return function($lname) use ($honorifics) {

        return "$honorifics $lname";

        };

    }

Call the three functions listed above, write the following code in lessons12b.php.

            // Recursive Functions

            title("3. Recursive Functions");

            echo "<p>factorial (10) - factorization.</p>";

            echo "<p>Factorization of the number 10 is: " . factorial(10) . "</p>";

            // Anonymous Functions

            title("4. Anonymous Functions");

            echo "<p>hello (fname) - regards.</p>";

            echo "<p>" . $hello($fname) . "</p>";

            // Closures

            title("5. Closures");

            $mister = makeGreeting("Mr.");

            echo "<p>makeGreeting(lname) - add a honorific before the last name.</p>";

            echo "<p>" . $mister($lname) . "</p>";


Run the project again and see the result. It will look similar to the following image depending on the data you entered into the form.

Use PHP recursive functions, anonymous functions and closure in practice

Use PHP recursive functions, anonymous functions and closure in practice

Recursive functions are functions that call themselves. They are used to solve problems such as factorization or searching recursive structures such as trees. PHP supports anonymous functions and closures, which are functions without names, which are often used in functional programming or as callbacks. In the my_functions.php file, add the other three functions.

 // This is a variable function

    function helloWorld() {

        echo "Hello, World!";

    }

    $nameFunction = "helloWorld";

    // Function Overloading

    function sumNumbers(...$numbers) {

        return array_sum($numbers);

    }

    // Using functions in an OOP context

    class Calculator {

        public function multiplay(float $num1, float $num2) {

            return $num1 * $num2;

        }

    }

Call the three functions listed above, write the following code in lessons12b.php.

// Variable Functions

            title("6. Variable Functions");

            echo "<p>nameFuction () - displays the value of the function it took.</p>";

            echo "<p>" . $nameFunction() . "</p>";

            // Function Overloading

            title("7. Function Overloading");

            echo "<p>sumNumbers(...numbers) - sum numbers in the array.</p>";

            echo "<p>Sum of numbers 1,2,3,4 and 5 is: " . sumNumbers(1,2,3,4,5) . "</p>";

 

            // Using functions in an OOP context

            title("8. Using functions in an OOP context");

            echo "<p>Object -> multiplay(19, 75) - using a method from the class.</p>";

            $obj = new Calculator();

            echo "<p>Multiplay the numbers 19 and 75. The result is: " . $obj->multiplay(19, 75) . "</p>";

 

And last time, run the project again and see the result. It will look similar to the following image depending on the data you entered into the form.

Use PHP variable functions, function overloading and using function in OOP context in practice

Use PHP variable functions, function overloading and using function in OOP context in practice

PHP enables you to call functions using variables to store their names. While PHP doesn't directly support function overloading, you can achieve similar behavior using variable-length argument lists. In object-oriented PHP, functions within classes are known as methods. These methods can have different access levels: public, protected, or private. This covers the fundamentals of functions in PHP. We'll explore more advanced function concepts in future lessons. For a visual demonstration of this lesson, check out our accompanying video tutorial.


PHP - 12. Unlocking the Power of PHP Functions

 

  

 

 

 

 

No comments:

Post a Comment