All posts tagged PHP

Writing Functions In PHP – Default Values

Writing Functions in PHP – Introduction

Writing Functions in PHP – Flexibility

Writing Functions in PHP – Return Values

Writing Functions in PHP – Global Variables

We saw earlier how the numbers of arguments that were passed into a function needed to match the number of arguments that the function was defined with. But with default arguments, that’s not entirely true because we can set some defaults so that if it doesn’t get a value, it has something that it can assume, and this not only will make our functions more flexible but also error resistant. Let’s go ahead and try one now…

<html>
<head>
<title>Writing Functions In PHP - Default Values</title>
</head>
<body>
    <?php

        function paint($color) {
            echo &quot;The color of the room is {$color}.&quot;;
        }

        paint(&quot;blue&quot;);

    ?>
</body>
</html>

Output: the color of the room is blue.

That is a simple straight forward example. What if we didn’t pass a value into the function?

    <?php

        function paint($color) {
            echo &quot;The color of the room is {$color}.&quot;;
        }

        paint();

    ?>

Sure we will get an error message.

Output:
Warning: Missing argument 1 for paint()…
Notice: Undefined variable…
The color of the room is .

Functions With Default Values

In the example above, we can set a default value for $color, so that if it doesn’t get a $color, we have something to fall back on. We do that by simply putting in a normal equal assignment in the function right after the arguments.

    <?php

        function paint($color=&quot;red&quot;) {
            echo &quot;The color of the room is {$color}.&quot;;
        }

        paint();

    ?>

So now, “red” will be our default value if we haven’t passed any value to the function. In other words, if no value were passed into the function, use “red”! The default value is overwritten when you specify a value, otherwise the value will stay the same. Even though we didn’t ask for another argument, it went ahead and assume “red”. If instead we tell it “blue”, it goes ahead and uses “blue”.

So you can see how this is going to make our function a little more error resistant because it will not give us that big nasty error if we didn’t pass something in.

Flexible Functions With Default Values

Let’s go ahead and make this function even more flexible. Lets say we just are not going to paint the “room”, but instead we are going to paint the $room as a variable.

<html>
<head>
<title>Writing Functions In PHP - Default Values</title>
</head>
<body>
    <?php

        function paint($room=&quot;office&quot;,$color=&quot;red&quot;) {
            echo &quot;The color of the {$room} is {$color}.&quot;;
        }

        paint(&quot;bedroom&quot;,&quot;blue&quot;);

    ?>
</body>
</html>

Output: The color of the bedroom is blue.

So, this function takes two arguments into it and we must pass two values into it as well. Even though we didn’t pass anything into the function, it went ahead and made the assumption with the default value that we have declared earlier. All of this will work:

<?php paint(); ?>

Output: The color of the office is red.

<?php paint(&quot;bedroom&quot;); ?>

Output: The color of the bedroom is red.

What if we say “blue” and leave out the other one which is the $room?

<?php paint(&quot;blue&quot;); ?>

Output: The color of the blue is red.

It went ahead and says “The color of the blue is red.”, and why is that? This is because it’s going to still assume that the arguments are coming in the correct order. So we have to make sure that we always pass something in the right order.

Required Value vs Not Required value

Consider this example:

    <?php

        function paint($room,$color=&quot;red&quot;) {
            echo &quot;The color of the {$room} is {$color}.&quot;;
        }

        paint(&quot;bedroom&quot;,&quot;blue&quot;);

    ?>

Output: The color of the bedroom is blue.

We know this will work. $room is a required value and $color is not a required value, in this function. This means, a required value is a value that is having the highest priority for us, we want to make sure that we pass the correct value to this required value. Not like the $color value, which is not a required value, we can choose whether we want to specify the value or just let the function go ahead and assume for us.

If we did it the other way around and made our $color as the required value and pass in only one argument into the function:

    <?php

        function paint($room=&quot;office&quot;,$color) {
            echo &quot;The color of the {$room} is {$color}.&quot;;
        }

        paint(&quot;bedroom&quot;);

    ?>

Output:
Warning: Missing argument 2 for paint3()…
Notice: Undefined variable…
The color of the bedroom is.

This function will take “bedroom” as being the $room, and it’s going to ask for the required value which is the $color. We didn’t pass any value to the function for the variable $color. This will return an error message to us.

So you want to always make sure that your default values occur last in line. In other words, anything that is required needs to come first in the arguments list, anything that is optional needs to come later and the order of this doesn’t matter and you can’t skip spaces in between. So you need to pass in something along the way.

Conclusion

Another thing that I found helpful with default arguments is that you very quickly get a sense of what kind of information you’re expecting to be passed in to your function.

<?php function paint($color=&quot;red&quot;,$room=&quot;office&quot;) {?>

Clearly here, I am looking for a color, I know it is going to be “red” and I am looking for a room which I know is something like an “office”. This gives us some context for knowing what those variables actually mean in our function.

Now that we’ve looked into default argument values, I think we’ve explored enough of functions that we will be able to get a lot out of them once we start coding and developing.

Thank you and enjoy learning.

Writing Functions In PHP – Global Variable

Two see the previous tutorials click the following links.

“Writing Functions In PHP – Introduction”.

“Writing Functions In PHP – Flexibility”.

“Writing Functions In PHP – Return Values”.

Global Scope Variable vs Local Scope Variable

Take a look at the following code, and give it your best guess whether it’s going to come back with “outside” or “inside”?

<html>
<head>
<title>Writing Functions In PHP - Global Variable</title>
</head>
<body>
    <?php

        $bar = &quot;outside&quot;; // global scope variable

        function foo() {
            $bar = &quot;inside&quot;; // local scope variable
        }

        foo();
        echo $bar . &quot;<br>&quot;;

    ?>
</body>
</html>

Output: outside

Why does it output “outside” instead of “inside”?

This is because the variable $bar (local scope variable) inside of the function has no relationship to the variable $bar (global scope variable) that was on the outside of the function. The variable inside of the function doesn’t know what value $bar is and has nothing to return out of the function. So it took the original value of $bar which is global scope variable that is “outside”. Let us see another example.

Now, take a guess whether it’s going to come back with “outside” or “inside” with this one?

<html>
<head>
<title>Writing Functions In PHP - Global Variable</title>
</head>
<body>
    <?php

        $bar = &quot;outside&quot;; // global scope variable

        function foo2($var) {
            $var = &quot;inside&quot;; // local scope variable
            return $var;
        }

        $bar = foo2($bar);
        echo $bar . &quot;<br>&quot;;

    ?>
</body>
</html>

Output: inside

Yes, it’s going to display “inside” for this function. We’ve set the value for the variable $bar to “outside”, pass it as an argument into the function foo2(). The function received it and reset them with the value “inside”, a function’s local variable, and later on return back the value out of the function which will be assigned to the variable $bar.

There is another way that we can do this kind of variable declaration, that is by using Globals.

Global Variable Declaration

Referring back to our first example,

    <?php

        $bar = &quot;outside&quot;; // global scope variable

        function foo() {
            $bar = &quot;inside&quot;; // local scope variable
        }

        foo();
        echo $bar . &quot;<br>&quot;;

    ?>

The variable $bar which is on the outside of the function is considered as a global variable. It has a global scope. It can be accessed anywhere inside the same page that we are working with. What ever happens inside the function is considered a local variable. It’s local only to the function and it doesn’t exist in the global scope. Anyway, we can change that by simply saying “Global $bar” inside of the function.

    <?php

        $bar = &quot;outside&quot;;

        function foo() {
            global $bar; // declaring global variable
            $bar = &quot;inside&quot;; // local scope variable
        }

        foo();
        echo $bar . &quot;<br>&quot;;

    ?>

Output: inside

What we are doing here is that we’ve told it to pull in that global variable $bar, go outside of the function and grab the variable for $bar, the global scope and pull that in so we can use it inside the function.

When the function finished execution, any changes that we’ve made to the variable $bar inside the function are going to be to that variable, no matter whether if it is a global scope variable or a local scope variable. In other words, the changes that we’ve made to the variable $bar inside the function are going to reset any other variable $bar outside of the function.

Method Comparison

When using global variable, you want to be careful because once you’ve declared something global, you’re effecting what happens outside of the function. So my advice is, use it with caution. You might be better off, passing in a variable into the function like we did in the second example.

If you are sure that you want to use your variable globally, then it is fine to declare your variable as global, but if you want to keep track on the values as they move around your script then you will declare your variable as a local variable. It’s a stylish choice that you’ll have to make. Here is the functions comparison that produces the same end result.

<html>
<head>
<title>Writing Functions In PHP - Global Variable</title>
</head>
<body>

    <?php

        /* using global variable */

        $bar = &quot;outside&quot;;

        function foo() {
            global $bar; // declaring global variable
            $bar = &quot;inside&quot;; // local scope variable
        }

        foo();
        echo $bar . &quot;<br>&quot;;

    ?>

    <br>

    <?php

        /* using local variables, argumants and return values */

        $bar = &quot;outside&quot;; // global scope variable

        function foo2($var) {
            $var = &quot;inside&quot;; // local scope variable
            return $var;
        }

        $bar = foo2($bar);
        echo $bar . &quot;<br>&quot;;

    ?>

</body>
</html>

Now we are ready to look at how we can set some default values to the arguments that can pass into a function so that a function can have some reasonable default values in case the user doesn’t pass in information or an argument into the function.

We will do that in the next tutorial in this series which is the final topic that we will be discussing about php function.

Writing Functions In PHP – Return Values

If you are new to this series please check out the other previous tutorials:

“Writing Functions In PHP – Introduction”.

“Writing Functions In PHP – Flexibility”.

Referring back to our previous overtime() function:

<html>
<head>
<title>Writing Functions In PHP - Return Values</title>
</head>
<body>
<?php
    /* declaring our third function */
    function overtime($salary, $month, $day, $rate){
        $hourly_pay = ($salary / $month / $day) * $rate;
        echo $hourly_pay;
    }
    overtime(2000,24,8,1.5); /* passing four arguments into the function */
?>
</body>
</html>

Output: 15.625

Function With Return Values

We know that we must get the value out of the function (instead of just displaying it in order for us to keep using it and keep working with it even if the function has finished execution. In order to do that, we need to return the value of $hourly_pay from the function and that’s just done with simply the word return, that’s the function that we are calling. We are telling the function, return this value!

It also is going to exit out of the function at that point when we say return. It’s a lot like break was when we were working with the loop. Let’s update our overtime() function so that it can return a value out of the function. The only thing that you should do is to replace the word “echo” with “return” and some modification in how we call the function.

<html>
<head>
<title>Writing Functions In PHP - Return Values</title>
</head>
<body>
<?php
    /* declaring our third function */
    function overtime($salary, $month, $day, $rate){
        $hourly_pay = ($salary / $month / $day) * $rate;
        return $hourly_pay;
    }
    $returned_value = overtime(2000,24,8, 1.5);
    echo $returned_value;
?>
</body>
</html>

So we called the function overtime(), we are going to return the value $hourly_pay to $returned_value and then echo back the new value.

Now, its a good idea whenever we are working with functions, especially functions that don’t just do display like we did with say_hello(), that you  always return a value out of them. Just get in a habit of making sure every function has a return. Maybe all it returns is true or false based on whether it works successfully, but we want to have something returned out of the end of that function just to let you know.

So for our say_hello() function, we should write something like this:

<?php
   function say_hello(){
     echo &quot;Hello World!&quot;;
     return true;
   }
   say_hello();
?>

So, a quick tip for you. You could actually have several return values inside a function. You could have it like this:

<?php
   function multiple_return($val2, $val2){
      if this happens{
         return this value;
      }
      if that happens{
         return this value;
      }
   }
?>

You could even have a function that had dozens of return value in it and a final return value at the very end of the function so that if none of the others were true, non of the others happen, than it would return something like FALSE or a DEFAULT value, which is a topic that I’ll be talking about in the final tutorial series.

Of course if I am returning a value, then I also have to receive (or catch) the value at the other end. Unlike say_hello() function where I called it on it’s own,

<?php
   function say_hello($word){
     echo &quot;Hello {$word}!&quot;;
   }
   say_hello(&quot;Everyone&quot;);
?>

I set it to the variable $returned_value so I can echo it back.

<?php
    $returned_value = overtime(2000,24,8, 1.5);
    echo $returned_value;
?>

The next return value tip that I want to tell you about is that return values return one and only one value. If you need to return more than one value, there is a way to do that.

Function With More Than One Return Values

For this, let me explain in a new example.

<html>
<head>
<title>Writing Functions In PHP - Return Values</title>
</head>
<body>
<?php
    function add_subt($val1, $val2){
        $add = $val1 + $val2;
        $subt = $val1 - $val2;
        return $add;
    }
?>
</body>
</html>

This function will take the two values I give it, it will do both addition and subtraction, and right now it’s going to return addition. Subtraction will just get lost like nothing ever happen. We can’t return more than one so we have to choose. But what if we want both?

Array is going to be our friendly solution here. Let’s see how array can help us.

<html>
<head>
<title>Writing Functions In PHP - Return Values</title>
</head>
<body>
<?php
    function add_subt($val1, $val2){
        $add = $val1 + $val2;
        $subt = $val1 - $val2;
        $result = array($add, $subt);
        return $result;
    }
    $result_array = add_subt(10,5);
    echo &quot;Add: &quot; . $result_array[0] . &quot;<br>&quot;;
    echo &quot;Subt: &quot; . $result_array[1] . &quot;<br>&quot;;
?>
</body>
</html>

Output: Add: 15
Output: Subt: 5

Let me guide you in the solution provided.

$result = array($add, $subt);

The reason we use array is because array simply takes variables and puts them into a single structure and assigns it to a single value like the above example. So when we want to echo both of the returned values, we call them like so:

    $result_array = add_subt(10,5);
    echo &quot;Add: &quot; . $result_array[0] . &quot;<br>&quot;;
    echo &quot;Subt: &quot; . $result_array[1] . &quot;<br>&quot;;

The number in the bracket [0] and [1] indicates the $add and the $subt variable from the function attributes that we called earlier: array($add, $subt); So [0] for additional and [1] for subtraction.

So that’s the way that we can pass multiple results out of the function. So if we need to pass something more that just one value, we can do it with an array.

Now that we’ve talked about return values. We’ve seen how a functions can do it’s processing and return a result back to what ever called the function. Next, we will look into Global Variables, a variable that is accessible from any method, procedure, or function and whose value can therefore be changed anywhere in the application.