Custom PHP functions
Sep 20
As I’d promised, today I’ll teach you how to create your own functions to assist you in your programming.
It’s pretty simple, but some people might not be able to grasp the concept so I’ll try to make things clear for everyone
On to the tutorial!
Recap
In our previous tutorial, we learned that functions could have return values or not:
Example 1: last lesson
<?php // Yodeling doesn't really bring anything but attention. yodel(); // Encrypts a string then returns the result, known as a hash. // This function is built-into PHP and is good for security. $hash = sha1('String'); ?>
I wanna make a basic one!
Let’s start with the famous Hello World function, shall we? This function won’t have a return value, we’ll create another function with one in the next page
Let’s try to call a function named hello_world() and see what happens…
Example 2: calling a custom function
<?php hello_world(); ?>
Oops…
Fatal error: Call to undefined function hello_world() in D:\NOVALISTIC\3.0\example.php on line 3
We haven’t introduced PHP to our hello_world() function. It doesn’t know what we want this function to do and we have to guide it. Computers and programs are highly renowned for their ability to only shut up and follow exactly what you tell them to do.
To declare a function, you need to first add a keyword function. Yeah, it sounds really obvious doesn’t it (I’m shouting out to VBScript and Perl, both of which use sub instead of function to declare custom functions)? Next, name your function, add a pair of parentheses ‘()’ and a pair of curly braces ‘{}’, and we’ll call the function immediately after defining it:
Example 3: structure of a function declaration
<?php function hello_world() { } // Call our function hello_world(); ?>
You don’t have to place the opening curly brace on another line. That’s just my own coding standard (shared by many other developers though) to make code blocks clearer. You could always place your brace on the same line as the first: function hello_world() {.
Calling our function now does nothing. PHP doesn’t spit any errors. That means our function was defined successfully and PHP had absolutely no problem with the job.
But… there’s nothing between the curly braces. Precisely why nothing happens. PHP thinks hello_world() does nothing. Let’s get it to do something, and I think you know what I want this function to do…
Add an echo command between the curly braces like so, and test/refresh ur PHP script.
Example 4: adding an echo command
<?php // This function just prints 'Hello World!' function hello_world() { echo 'Hello World!'; } // Call our function hello_world(); ?>
Hello World!
If you got exactly that message ‘Hello World!’, then congratulations you’ve just made your first function! But functions don’t have to be limited to echoing simple sentences like that.
Turn over to define another function that returns a value instead.
Pages: 1 2