Learning PHP - Part 5 - Lets make it functional
Part 5
Laracasts main site
Laracasts - PHP for beginners
Chapters covered:
Chapter 10 - Functions
Functions are simple, but very powerful reusable pieces of code. They are the building blocks of any language. Lets see how they help shape PHP.
// index.php
<?php
// Will echo the values of $one, $two, and $three onto your web page
function dumper($one, $two, $three){
var_dump($one, $two, $three);
}
Lets break it down.
function
: This tells the PHP interpreter youre defining a function
dumper()
: ‘dumper’ is the name of the function when you call it
($one, $two, $three)
: These are whats called “arguments” or
“parameters”. These are what are passed into the function, this can be blank.
{
var_dump($one, $two, $three);
}
This calls the function:
var_dump()
This will output your variables onto the page.
Lets get a little bit more advanced. Lets create a dd() function.
// index.php
<?php
// Die and dump
function dd($val){
echo '<pre>';
die(var_dump($val));
echo '</pre>';
}
// Will stop anything after this function
dd('hello world');
// Will not run
dd('hi there');
Lets look at what dd($val)
is doing.
So first, it defines the function dd, then it will take in a 1 variable argument.
Next, it will wrap the value of die(var_dump($val)
inside of <pre></pre> tags.
Finally, it will kill the execution of the php program. Equivalent to exit
.
Homework
Assume you own a night club. Only allow people 21 or older inside and print a message
telling them if they’re allowed to come in.
My solution:
// functions.php
<?php
function isOldEnough($age){
return ($age >= 21 ? true : false);
}
function echoOldEnough($age){
echo '<p>';
echo 'You are, ' . $age . ". ";
echo (isOldEnough($age) ? "You can enter the club." : "You cannot enter.");
echo '</p>';
}
// index.php
<?php
require 'functions.php';
echoOldEnough(21); // is allowed inside
echoOldEnough(20); // is not allowed inside
I’m not going to go too in depth, but basically echoOldEnough()
is a wrapper around
isOldEnough()
. This allows you to print a readable message on the webpage.
This function is imported into ‘index.php’ when you run:
require 'functions.php';
Lets go to Chapter 11 in the next part.
Links
Follow along with my repo
Laracasts main site
PHP for beginners