Unlimited Arguments and Return Type of Function
Md Jannatul Nayem
Posted on March 11, 2023
Sometimes you may not know how many arguments will be passed to your function in advanced. So you should handle the situaion. Before we had to manage it manually but right now php has builtin features for unlimited arguments. Behind the scene it creates an array to store the rest of arguments.
Suppose In my home, my two friends and their family memebers will come to visit. Here two friends are confirmed as a guest and rest are unknown and unlimited. Here is an example:
<?php
function guestList(string $friend1, string $friend2, string ...$others){
echo "Confirmed Guests are: " . $friend1 . " " . $friend2 . "\n";
echo "Unknown are: \n";
foreach($others as $name){
echo "$name\n";
}
echo "\n";
}
guestList("Gourango", "Nayon", "a", "b", "c", "d");
Decalaring a return type of a function explicitly sometimes helps a lot when debugging. You will face fatal error if you accidentally return such a value which is mismatched with decalared return type.
Suppose you want to calculate your age and you want to get only years. Then the return type should be integer. Because nobody tell i am 26.7 years old.
<?php
function calculateAge(string $birthday):int{
$timeZone = new DateTimeZone('Asia/Dhaka');
$age = DateTime::createFromFormat('d/m/Y', $birthday, $timeZone)->diff(new DateTime('now', $timeZone))->y;
return $age;
}
$age = calculateAge("27/08/1993");
echo "you are $age years old\n";
echo "\n";
If you don' return integer you will face a fatal error here.
A little Tips:
If your function gets too much big and starts doing more than one work you can decompose the function into smaller chunks.
Posted on March 11, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.