Tags

, , , , ,

test1//embedr.flickr.com/assets/client-code.js

Creating your own functions in PHP is our next big step in web programming. You’ve already seen a few built-in PHP functions already.
What are functions? The functions are the callable sections of your code where you can pass data and it returns data to you. Do you have some parts of code to run multiple times in your code? Put them into a function. Got some code that shouldn’t run automatically when the page loads? Put it into a function. Is there a too long code that is difficult to debug? Break it into several functions so that you can pinpoint the error easily.
Now, let’s try to understand it from a different point of view.

object-oriented-design-patterns-in-php7 for web

object-oriented-design-patterns-in-php7 for web

In any language, “Noun, Adjective, Adverb, Pronoun, Articles” do not do anything. They definitely take part in the action. But without the verb an action remains incomplete. Functions in PHP play the same role. This is the action part. You pass some data and the functions return you some data. Try to imagine a simple function where you pass two integers and the function adds it and gives you back the result.
I hope it helps.
By putting code into a function, you actually convert it into action-verb. Such as, you’re putting some air in a function and when you call it, it generates electricity. Think this way; you pass ‘air’ data into a function and it returns ‘electricity’ data.
So we learn a very important thing. If I pass data to a function, it returns data. You’ll find this concept in every programming language. But PHP has some unique features.

I’m a Full-Time writer. If you find these articles helpful please consider buying any of my books.
You can buy from either Leanpub or
Amazon or from my publisher
Apress.

Remember, it’s just the beginning of an interesting journey. You are going to learn how to divide up your code. Learning functions is the precursor to the next big thing – object oriented programming (OOP). In the next chapter we’ll learn how OOP lets you wrap both functions and data into classes and objects, so that the coding becomes easier.

BASIC FUNCTIONS WHERE WE PASS SOME DATA

How do you build your own function?
It’s very easy. The structure is like this:
function function_name ([argument_list_to_pass_data]){
“””Some statements, works to be done”””
return Returning_data
}
If you’re complete new, this example really doesn’t make sense. So let’s see some real-world-examples. Imagine a situation, where a user visits your website. The user logs in, so that your website automatically knows that username and greets him or her.
You need to write several functions until you reach the end. But we can, at least, write a very simple function to understand the core conception. Suppose the user’s name is Sanjib.


function GreetingsDisplay($message, $username) {
    
    return $message . " " . $username;
    
}


echo GreetingsDisplay(“Hello”, “Sanjib”);
The function greets you with the message – Hello Sanjib.
People describe science as the greatest adventure in this world. I think learning php is no less. Let’s be more adventurous and build a little bit more complex application.
In this application, we pass an array of numbers through a function and get the average of that number.
Remember, if you don’t pass any number, it’ll give you an output like this – “No Input”.
Here is the example code:



                // suppose we have some numbers in array
                $numbers = [];
                
                echo averager($numbers);
                
                function averager($array) {
                    
                    $TotalOfTheNumbers = 0;
                    $average = 0;
                    $NumberOfNUmbers = 0;
                
                    foreach ($array as $value) {

                        //the total of the numbers
                        $TotalOfTheNumbers = $TotalOfTheNumbers + $value;

                    }
                    //how many numbers ar there
                    $NumberOfNUmbers = count($array);
                    
                    //if there is no input
                    
                    if(count($array) > 0){
                        
                        //we'll get some verage value
                        $average = $TotalOfTheNumbers/$NumberOfNUmbers;
                        return $average;
                        
                    }
                    else{
                        
                        echo 'No input';
                        
                    }  
                    
                } 
                

Functions are integral parts of your web application. The basic duty of a function is – it gets data inside and gives an output. This output may become inputs of another function; and your application grows.
PASSING BIG DATA THROUGH FUNCTIONS
Now the time has come to take the stage for the big moment.


                
                $num = 4;
                
                //we want to square the value in a variable
                //will that change the original value?
                //the answer is NO

                function squarer($number) {
                    
                    $number *= $number;
                    return $number;
                    
                }
                //before the function call
                echo "The original value - " . $num;
                
                squarer($num);
                
                //after the function call
                echo "After the function call, the original value remains same - " . $num;
                
                
                /*
                 * our conclusion:
                 * the function could not change the original value
                 * a copy of that value was passed and the original value remained unchanged
                 * But, if we pass the value by reference, the original value is also changed
                 */
                
                function passByRef(&$param) {
                    
                    $param *= $param;
                    return $param;
                    
                }
                
                passByRef($num);
                //after the new function call
                echo "After passing data by reference, the original value takes the new value - " . $num;

                

This function is a big deal. Why? It’s because, you have learned how to pass data by reference and thereby change the actual value.
We have declared a number and assign a value – 4 to it. Now, we have passed that number through a function that multiplies that number by itself making it 16. But the number has not changed. Why it happens? It happens, because, generally, when we pass any value through any function, a copy passes through it. Not the original one. The original one remains unchanged.
Now look at the second part of the above code.


function passByRef(&$param) {
                    
                    $param *= $param;
                    return $param;
                    
                }
                
                passByRef($num);
                //after the new function call
                echo "After passing data by reference, the original value takes the new value - " . $num;


This time we have passed the value by reference and the original value changes. The original value was 4. Now it is 16.