Jump to content

PHP Fundamentals IV
   (0 reviews)

Arceus
  • Part of a guide series, the PHP Fundamentals guide dives into the very basics of PHP and how it works, designed for people that have never worked with PHP at all, or only very briefly (or people that just want more solid info on the ostensibly easy stuff). This series is designed to build on itself, because PHP is like algebra, you can't just dive straight into the middle. ... well, you could, but it wouldn't be pretty. Fundamentals IV covers functions.

    Type: PHP

PHP Fundamentals IV:
Functions

Welcome back to PHP Fundamentals! We're here with PHP Fundamentals IV, covering functions. Oh, goodie, yay, my favourite thing! I love functions, really, probably a good thing given I have to write a lot of them, and most large PHP scripts are coded with many, many functions in them, so anyone interested in working with PHP should know what they are, how they work, and how to make friendsies with them.

 

Now, you can, probably, manage to do some semblance of function work on phptester.net, it's a free-for-public-use PHP sandbox to play in, but it may not work out so well. I'll try and write this guide around assuming you need to be able to do it on there. Let's gogogo!

 

WHAT IS A FUNCTION?

Functions are sort of like a file in a file. They have different scopes, and do not run automatically when accessed like a typical PHP code in a file would. Anything in a function must be called by the function's name before it runs. This is useful in large PHP scripts, in order to write everything a script may need to be able to do, without causing it to fire constantly. If you had a few thousand PHP operations all firing at once per page load, you'd pull your server down pretty quick, fam. So instead, we contain each of these related operations into functions!

 

Not only does this save your server resources, it also just kind of makes sense. Each related operation is in the same function in sensible order, or at the very least, all call each other. It depends on the specific set up of the script, and what it aims to achieve. Functions are all contained within curly braces ( {} ), and PHP is quite sensitive about how many there are, and where they are, so be careful moving braces, parentheses, apostrophes, and semicolons around (dot your I's and cross your T's).

 

WRITING A FUNCTION

So how is a function structured and written?

 

First, we start off with a basic function structure.

function TestFunction()
{
}

Now, we've named this function TestFunction, so we should remember this name. Ideally, you'd name your functions in some manner that indicates what it's for, which makes it easier to remember. You'll also want each function's name to be unique, as if you try writing multiple functions called the same thing, everything gets confused (not least of all you), and the PHP script will just, die (cannot redeclare FunctionName(), previously declared in FileName.php at line two - no I haven't seen this error many, many times, what, I am the perfect).

 

Do we want globals, here? If we want any global variables to be usable within the function we are writing, we'll need to declare them on a global line at the top of the function.

function TestFunction()
{
	global $globalvar;
	// Don't worry, if you need a global later, you can just add this line to the top of the function
}

Here on out, we can write our code! Let's do something simple, just a quick echo, so we can see how this works.

function TestFunction()
{
	global $globalvar;
	// This is really just an example of how to call globals, and you can take this and the line above it out, they're really quite unnecessary.
	// By the way, this is how you comment in PHP code!
	/* You can also do it this way, similar to how it's done in CSS,
	it is easier for more than one line of comment. */

	echo 'Hi, I work! I am being called from TestFunction!';
}

And now, we can use it! But how?

 

CALLING FUNCTIONS

Because this function is a very simplistic one, we really don't need a function for this, so for the sake of examples, let's pretend this line is pulled from a MySQL query. A MySQL query would access the site database, select a row, or several, arrange the data it receives into a string or an array, and then send that data to wherever you trigger this function from. Because all this function does is echo out a line, you can use it very simply. Beneath your function, type this:

TestFunction();

… and save or test the code. Pretty cool, huh? Unlike with variables, you don't need to echo a function if it, at some point, echos itself. It depends on how, exactly, the function is structured and written that determines how you use it. For functions that return data, you'll likely want to call them into a variable as a value. Those that simply echo something can be called either just like this, or within surrounding HTML, as below:

echo '<div>
	',TestFunction(),'
</div>';

If, at any time, you are ever not sure exactly how a function operates, try a few ways; you'll start to understand how to use it better, and when faced with similar functions later, know exactly what to do.

 

FUNCTION ARGUMENTS

What are these parentheses after the function name, and what are they for?

 

These hold function arguments. Much like PHP operators, functions can take extra arguments and pass data from one function to another in this way. Passing data between one function and another is paramount in most PHP scripts; your script functions and files need to have a way to pass information between them. If you need to fetch this data repeatedly across many files and functions, it tends to cause some slow-down; this is partly alleviated by globals, and partly alleviated by arguments.

 

Let's do this: Say we have an echo line that needs to change based on a transient data variable. We could just echo this out into a line, and use the variable in place of it. Alternatively, we can get nerdy, and also somewhat inefficient (don't do specifically this, this way, this is just for example and learning purposes), and pass this variable to a function, and then let the function sort it out. Most often, you'll need to pass IDs or such to a function in order for it to run correctly; can't look up a thing or change a thing without an ID, usually, so passing user IDs and message IDs, for instance, around between functions, happens a lot.

function TestFunction($variable)
{
	echo 'The result is '.$variable.'.';
}

$variable = 'seriously, dont do exactly this in production, it is bad coding';
TestFunction($variable);

Ta da! You can pass integers, strings, and arrays, through function arguments, to be used within the function for whatever operation it's needed for. To pass raw data, surround strings in apostrophes (TestFunction('this is what it prints');), but integers can be passed without them. These can also be set to null (no apostrophes, treat it like an integer), but depending on what it's used for on the function's end, it may cause some errors.

 

Remember that whatever you declare the variables as being called in arguments when the function itself is written is what they'll be called when being used in it. Ergo, if you create MyAwesomeThing() and declare it as function MyAwesomeThing($id, $name) {}, whatever variables are in those two positions will be called what they are there. Calling MyAwesomeThing($number, $user); will not cause those variables to suddenly become $number and $user in the function; they're still $id and $name. For your own sake, just call them the same thing on both ends, where possible, it's easier to remember.

 

While you can send a sub-variable from an array through arguments, I wouldn't call it that on the other end (i.e. MyAwesomeThing($user['id'], $user['name']) should not still be function MyAwesomeThing($user['id'], $user['name']) {} in the function itself. Don't do that, pls, this is actually a bad way of forming an array). In some software, functions are also used for the theme templates, and are called by function name into the theme structure. Pretty useful to know if you intend, and I'm sure many of you do, to get into theming at some point. This can mean that your software has dozens of templates, not just one or two, in each template-related file.

 

Bear in mind that arguments the function asks for that are left blank will cause an undefined error. To prevent this, in case of arguments not always having valid data, you can define them in the function declaration:

function TestFunction($id = 0, $name = 'Guest')
{
}

Should a variable with a valid value be passed in its place, the default declarations will be overwritten, otherwise it will use what you set as default.

 

RETURNING DATA

Finally, we have returning data from a function process to another function. I do this all the time, my favourite thing. Let's say, for whatever reason, you needed to pull a username, which, for whatever reason, isn't loaded automatically. You do have the user's ID, however. Most likely, you'll want to run an SQL query that checks the members information table for a record matching that ID, and then returns the user's name as stored in the database. Then, you'll need to send this result back to the function that requested it.

 

Let's vaguely kinda do this really quick.

function iGetUsername($id)
{
	$return_me = array();

	$return_me = array(
		'id' => $id,
		'name' => 'Name',
	);
	return $return_me;
}

$userid = 1;
$user = iGetUsername($userid);

echo '<pre>',print_r($user),'</pre>';

As you can see, iGetUsername() takes the ID it is sent, and then arranges it into a short array with the ID and username in the same bit. Then, it sends the array it just built to the variable that called the function. Quite easy, really!

 

CHEEHOO I love functions!

 

Now, you know how a function works, how to write one of your own, and hopefully what to look for when editing one, as well as how to use some basic arguments in a function. Next up, we'll tackle PHP $_POST forms! I love those too, you know, when I'm not trying to do something stupid complex and it just ain't workin' for me. We're close to the end of PHP Fundamentals' end, so, stay tuned, and we'll wrap this guide series up soon! I'm pretty sure the Forms guide will be the last.


Related Guides

  • Kit the Human

    IPS is a powerful product. Most of the time, if I need to achieve something, I can do it with page blocks. Sometimes, I just need to alter those page blocks a little bit in order to achieve what I want to achieve.

     

    In this guide, I hope to help guide you through looking for the correct variables and writing a simple if statement. At the end of the guide, you should have a working automatic open thread list.

    IPS




User Feedback

Create an account or sign in to leave a review

You need to be a member in order to leave a review

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

There are no reviews to display.


×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use, Guidelines and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.