Basic PHP: The Full Language Introduction 2
Ello, ello, ello ...
How are you ?
Did you manage to make that Lobola money? Oh Lobola is a South African tradition, where a man pays/gives gifts/monies to the wife's family. It's so much fun.
"Alright, Okay ..." - Denzel Washington
Alright take a breather Khomotso, let it sink in a bit and come back :)
"Alright, alright, alright ..." - Kevin Hart's Dad
PHP has three main variable scopes:
PHP Functions
Once again, a function is a block of statements that can be used repeatedly in a program. A PHP function is defined as shown below
<?php
function nameFunction() {
//function code to be returned here inside
}
?>
<?php
function sayHello(){
echo 'hello world1!';
}
//calling the function
sayHello();
//calling the function will print 'hello'
?>
As usual Pedro, create a new PHP file called 'functions.php'
, get your ide/text editor ready, because we're about to get our code on. Alright copy and paste the code below, and let's get cracking ....
<?php
function printText(){
echo 'this text is from the function';
}
printText();
?>
<?php
function testArguments($name){
echo 'your name is '.$name.'!';
}
// caliing function with our argument
testArguments('Thandi');
?>
'functions.php'
file will ya. Reload the page in your browser and voila! ... your name is printed as is shown in the code.
Be mindful that a function can take as many arguments as your pretty brain can take. like so :
<?php
function testArguments($name, $lastName){
echo 'Your name is '.$name.' '.$lastName;
}
testArguments('Thandi', 'Swanepoel');
?>
Default values for our arguments, these are the values that will be used instead of our arguments in case they are empty. Like so ...
<?php
function defaultArguments($name = 'default name'){
echo 'The name value is '. $name;
}
defaultArguments('Sthembile');
defaultArguments();
defaultArguments('Danng Ma!');
?>
<?php
function addition($x, $y){
$sum = $x + $y;
return $sum;
}
echo addition(5, 1);
?>
"Functions are a collection of one or more php statements stored in a block, that can be called/referenced and used at multiple points of a PHP script for multiple times"
The Village Geek
"Alright, alright, alright ..." - Matthew McConaughey
Play around with the code will ya ... It'll be a good decompression for you.
Talk to you next time ...
Cape Town, South Africa