Thursday, 22 October 2015

#PHPro.: Become a Master of PHP +3: Custom Functions

Yo, geeks and... humans. Let's get started with functions.
What are custom functions?
Let's say you want to create some lines of code, and you know you're going to need it again. Hell, you're probably going to want to use it like a million times. What do you do? Copy and paste it a million times? Nah, man. I'm not asgardian. You build a function, that way, all you have to do is call the function and that process will run.
Examples.

<?php 
    $num1 = 4555;
    $num2 = 99;

    function add() {

     $sum = $num1 + $num2;
     echo $sum;
    }

// What this function does is, it will add the two numbers, save the sum in the variable $sum and echo
// But it won't do anything until we call the function. So let's do that.

add();
?>

It's as simple as that. But its very important. You're going to need functions a lot so you need to have this registered in your brain.

Functions with parameters

You might have been wondering what the hell were those brackets doing up there in function add()? If you hadn't, I'm sorry for you. You have no imagination at all. Just kidding! You're alright. Let's explore these parameters.

Parameters make our functions a lot more flexible. Pay attention.

<?php

function add($num1,$num2){ //yep, we declared our numbers right in here
       $sum = $num1 + $num2;
       echo $sum;
// so now, where the hell are the numbers we're adding???
// that's the fun part. We write the numbers we want to add when we call the function
}

add(555,419); // Done. Cool, right?
?>

Return value
In the php code above, if you try to use the variable $sum anywhere outside that function, you'll get an error. Why is that? Because the variable is only for use within the function. Yeah, what is with them, right? But you can infact make it visible outside by returning it. Like, just type return $sum and that's it. You can use it outside.

Global variable and scope
When something is global, it can be used everywhere. When its local, it can only be used within. Just keep that in mind. Its like world news and local news. To make something global, all you have to do is type global before it and you're good to go.

<?php

function add($num1,$num2){
       global $sum; // this makes $sum global
       $sum = $num1 + $num2;
       echo $sum;

}

add(555,419);
echo $sum// now you can use it outside
?>

Constants
One more thing I need to discuss is constants. These are used to contain values like variables, but once you declare a constant, it cannot be changed. It will forever be trapped in the gates of Valhalla.
How do you declare a constant? Just like a variable, but without the $. Just remember it as the variable's broke cousin, right?

Word from sensei
A man who can't create and manage PHP functions seamlessly is like a carriage without a horse... Stagnant.

That will be all for now. In-built php functions up next. Stay tuned.

No comments:

Post a Comment