PHP Tutorial

PHP functions and strict types

? ?

What are the PHP functions and how we create one?

A function is a group of statements that can be called multiple times across our script. By using functions we can avoid repetitive code by writing once our statements (the code) inside the function and using it multiple times when we need it.

The functions help us to make our code cleaner, easier to write and easier to change it (once you update the function, it will also be updated everywhere it's used).

<?php

//here is where we define/create the function
function getGreetings()
{
   //here is the function's body
   echo 'Welcome to RedTutorial.com. Have fun!';
}

//and here we call/execute the function
//this will execute the statements inside the function's body
getGreetings();
//will output "Welcome to RedTutorial.com. Have fun!"

//and we can call again and again the function
getGreetings();
//will return same output as before

As we can see from the example above, we must first use the keyword function before writing the name of the PHP function.

The name of the function follows the same rules as when setting the names of the variables (start the name with letter or underscore, after that you can use only letters, numbers and underscore). One exception is that the name is case-insensitive (PHP will see the uppercase and the lowercase letters from the name in the same way, so you could call later the "getGreetings()" function either by "getGreetings()" or "getgreetings()" and PHP will make no difference, but we should avoid confusion by calling them as we defined them initially).

PHP function's return statement

A function can also return a value from inside it's body.

<?php

function getSignature()
{
   return 'Kind regards, Will Smith';
}

//output signature text
echo getSignature();

The above PHP function will output the returned value "Kind regards, Will Smith". We can put more complex logic inside the function's body, and later based on  that logic return a value. We can return any type of value we want.

PHP function's arguments

Inside a PHP function we can pass values. To pass this values inside the function's body we use arguments. Arguments are defined at the top of the function, after its name, inside the parentheses.

<?php

function helloWorld($name)
{
   echo 'Hello, my name is '.$name.'.';
}

helloWorld('Mike');
/*
this will output 'Hello, my name is Mike.'
*/

helloWorld('Anna');
/*
this will output 'Hello, my name is Anna.'
*/

As we saw in the example above, our argument was '$name' and we use it to pass inside the function's body different values (first 'Mike' and then 'Anna'). We can set as many arguments as we want inside the function's body.

<?php

//shopping cart info function
function shoppingCartItem($product_type, $amount)
{
   //check product type
   switch($product_type)
   {
      case 'Coffee':
         $price = 1.2;
         break;

      case 'Cookies':
         $price = 2;
         break;

      default:
         return 'Product currently not available.';
   }
    
   return $amount.' x '.$product_type.' - total price: '.($price*$amount).'.';
}

//output the results
echo shoppingCartItem('Coffee', 2);

echo shoppingCartItem('Cookies', 3);

echo shoppingCartItem('Apple', 1);

We recommend that you keep the number of arguments to a minimum, so it will be later easier to understand what you are passing inside the function. If you use too many arguments maybe your function tries to do more than it should, and it would be better to split it in two or more functions.

PHP function's default argument value

An argument can also have a default value. If we don't pass any value for that argument, the default value will be assigned to the argument.

In the function from the bellow example we want to check if the user's current order value with the discount applied. By default the discount will be 0, so no discount by default, but we could also set a discount value for the total price.

<?php

function getOrderTotalPrice($price, $discount_percentage = 0)
{
   //calculate the total price
   $total_price = $price - ($price * $discount_percentage);

   //output the final price
   echo 'The total price of the order is '.$total_price.'.';
}


getOrderTotalPrice(40);
//the total price will be 40

getOrderTotalPrice(20, 0.25);
//the total price is now 15 (there was 25% discount)

getOrderTotalPrice(26);
//the total price this time is 26

PHP Strict typing

As we already learned, in PHP we can first give to a variable a string value and then, later on in our code, give to the same variable an integer value (a number), like in the example code bellow. This action is perfectly normal in PHP, since PHP automatically associates the data type (like string, integer, array ...) of the variable based on the value we give to it. This PHP behavior means that it is a loosely typed language.

<?php

/*
We don't need to specify the data type of the variable.
First we assign a string data type value to the variable.
*/
$promo_code = 'PHP tutorial';

/*
And now we change the value of the variable to an integer data type value.
This will not throw any error in PHP, the variable will automatically be converted 
to the integer data type since it's value is an integer.
*/
$promo_code = 3455;

Starting with PHP 7 we can specify which type of data we want our argument to be and also which type of data we are expecting the PHP function to return. This option is called type declarations. In the example bellow we have a 'checkIfAuthorised' function that expects the '$user_type' argument to be a string and to return a bool(true or false) data type of value.

<?php

/*
function to check user permissions
*/
function checkIfAuthorised(string $user_type) : bool
{
   //check if the user is admin
   if($user_type === 'admin')
   {
      return 1;
   }
   else
   {
      return 0;
   }
}

//set current user type
$current_user_type = 'admin';

//make user check
if(checkIfAuthorised($current_user_type))
{
   echo 'The user is authorised for this section.';
}
else
{
   echo 'The user is not authorised for this section.';
}

By default, even thought we put the type of data that can be passed and returned, we won't get any error if the rules are not followed. In the above example even though we specified that the function will return a bool type variable, we returned an integer (if the user was admin we returned 1, if not we returned 0). So, even though we returned a different type of value we didn't got any errors. 

To enforce the strict typing in PHP and throw errors if the type declaration are not followed we need to set 'declare(strict_types=1);'. This statement needs to be the first line on our PHP file, as in the example bellow. By using the strict declaration we can enforce that our PHP functions are used the way they were designed. 

<?php
/*
this statement will enforce strict typing
*/
declare(strict_types=1);

function getCouponDiscount(string $coupon_name, float $total_price) : float
{
   switch($coupon_name)
   {
      // 50% discount
      case 'WINTER_IS_HERE':
         return $total_price * 0.5;

      // 20% discount
      case 'SUMMER_HAS_COME':
         return $total_price * 0.2;

      // 15% discount
      case 'AUTUMN_RAIN':
         return $total_price * 0.15;

      default:
         return 0;
   }
}

$cart_total_price = 38;

// valid statement
$discount_value = getCouponDiscount('SUMMER_HAS_COME', $cart_total_price);

/*
invalid statement since the $coupon_name argument is an integer instead of string,
this will thrown an error like "FATAL ERROR Uncaught TypeError: Argument 1 passed to getCouponDiscount() must be of the type string, integer given..."
*/
$discount_value = getCouponDiscount(562, $cart_total_price);

How can functions help us?

What is the output of the following block of code?

<?php

function doubleNumber($number = 1)
{
   echo $number*2;
}

doubleNumber();