Konnor's Blog

Learning PHP - Part 5 - Lets make it functional

August 26, 2019

Part 5

Laracasts main site
Laracasts - PHP for beginners

Chapters covered:

Chapter 10 - Functions

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
// 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
// Die and dump
function dd($val){
echo '<pre>';
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 \

tags. Finally, it will kill the execution of the php program. Equivalent to exit.


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
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
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.


[Follow along with my repo](https://github.com/ParamagicDev/php-for-beginners)
[Laracasts main site](https://laracasts.com)
[PHP for beginners](https://laracasts.com/series/php-for-beginners)

Written by Konnor Rogers who currently works at VeueLive as a full time developer. You should follow him on Twitter