Creating first Function

I would like to learn how to create a Function in PHP.

(Hold my hand… I’m scared!!!) :frowning:

Here is some code that I have which is mucking up my page, and I’m thinking this might be a good candidate for a Function…


	// Display Online Status.
		$minutesOnline = (time() - strtotime($lastActivity))/60;

		if ($minutesOnline < 15){
			// Member Online
			echo '		<img src="/images/Light_Green_10.png" width="10"
							alt="Member Status: Online"
							title="Green Light.  Credit: 1RadicalOne, Wikimedia Commons." />
						<br />';
		}else if ($minutesOnline < 30){
			// Member Idle
			echo '		<img src="/images/Light_Yellow_10.png" width="10"
							alt="Member Status: Idle"
							title="Yellow Light.  Credit: 1RadicalOne, Wikimedia Commons." />
						<br />';
		}else{
			// Member Offline
			echo '		<img src="/images/Light_Gray_10.png" width="10"
							alt="Member Status: Offline"
							title="Gray Light.  Credit: 1RadicalOne, Wikimedia Commons." />
						<br />';
		}

Actually, I guess my first question should have been…

Can I assign echo statements like above to a variable? (I’m just used to saying $balance=100;)

If I could pass in the last time the Member was active and then get back the HTML I need to display the Member’s Online Status that would be helpful.

Sorry if this is a lame thread, but all part of being a newbie!!! :cool:

Debbie

Changes highlighted in red.


[color=red]function get_online_status($lastActivity)
{[/color]
		$minutesOnline = (time() - strtotime($lastActivity))/60;

		if ($minutesOnline < 15){
			// Member Online
			[color=red]$html =[/color] '		<img src="/images/Light_Green_10.png" width="10"
							alt="Member Status: Online"
							title="Green Light.  Credit: 1RadicalOne, Wikimedia Commons." />
						<br />';
		}else if ($minutesOnline < 30){
			// Member Idle
			[color=red]$html =[/color] '		<img src="/images/Light_Yellow_10.png" width="10"
							alt="Member Status: Idle"
							title="Yellow Light.  Credit: 1RadicalOne, Wikimedia Commons." />
						<br />';
		}else{
			// Member Offline
			[color=red]$html =[/color] '		<img src="/images/Light_Gray_10.png" width="10"
							alt="Member Status: Offline"
							title="Gray Light.  Credit: 1RadicalOne, Wikimedia Commons." />
						<br />';
		}

		[color=red]return $html;
}[/color]

Some follow up questions…

1.) Is it really that easy?

2.) Can you pass in multiple values into a Function?

3.) What is the scope of the $html variable?

4.) Can the $html variable hold any data-type?

5.) Where can I put the Function?

Can it reside inside my original script?

6.) I am not ready to use OOP, so how should I manage Functions?

Dump all of my Functions in one file?

One Function per File?

7.) If I put the Function is another file, how would I use it?

Thanks,

Debbie

Yup. :slight_smile:

Sure can. You pass them as a comma-separated list.

function get_online_status($lastActivity, $someOtherValue, $yetAnotherValue)

It’s local to the function. It won’t get or set any global values without your explicit say-so.

Yup.

Anywhere. It can even be defined later in the script from where it’s used (unless the function is included into your script).

The simplest thing you could do is just to create a functions.php where you keep all your functions, and include that into your pages.

One step further would be to group your functions into files by the kind of job they do. Database-related functions, template-related functions, security-related functions, etc.

You would include/require the file…

require_once ‘functions.php’;

…and from that point on, you can use the functions as if they had been defined in that very page.

[quote=“Jeff_Mott,post:4,topic:15504”]

It’s local to the function. It won’t get or set any global values without your explicit say-so.[/quote]

Are you sure about that?

If it is local to the function, then you could never call a function and use its results variable?!

Would you ever create one function per script? (I think that is how they do it in OOP with functions and classes?!) :-/

What do I need to do to error-handle things?

What happens if the file isn’t required properly or whatever?

BTW, can a PHP Function return multiple values back??

Thanks,

Debbie

That’s what the return statement is for. When you invoke the function, you would assign its value to a variable.

$returnValue = get_online_status(‘2004-01-01 13:00:00’);

One function per script isn’t standard practice, and I can’t think of how it might help.

In OOP, on the other hand, one class per script has a practical benefit. If you use a class that doesn’t exist, then PHP gives you an opportunity to find that class on the file system and load it. That process is called autoloading.

In function-style coding, your error handling options are limited. Your function can communicate that an error occurred either through a special return value, or by dieing.


function get_online_status($lastActivity)
{
		[color=red]// if strtotime fails, then it will return false
		// so let's test for that scenario
		$lastActivity = strtotime($lastActivity);
		if ($lastActivity === false) {
			// if the error was so critical that your script can't proceed
			// then you could run: die('Problem description')
			// and the script will terminate

			// in this case, you probably want to give your script a chance to recover
			// so we'll return a special value to indicate failure
			return false;
		}[/color]

		...
}

...

$returnValue = get_online_status('2004-01-01 13:00:00');

[color=red]// test if get_online_status failed
if ($returnValue === false) {
	// at this point, we have a few options depending on how critical this feature is to the script
	// we still have the option to die
	// or we could write to an error log or send an email
	// or we could just silently ignore the problem

}[/color]

Yup, by returning an array.

Thanks for the help.

Let me go off and try to write my first function - I guess you basically did for me?! - and I’ll be back with more questions, I’m sure!!

Debbie

Jeffs virtually told you everything :slight_smile:

Id add that if your unfamiliar, think of a function as a mini-program within your project, you write a function to perform a job that wil need doing lots of times throughout your script, then instead of writing the same code over and over you just call the function. The added benefit is when you change a function it changes all occurences within your script. ie if you had a function to work out salestax in chosen state, you may call that function 100 times on your site, but when you wanted to change the calculation you’d only need to change the function once. (I maybe teaching you to suck eggs here)

Personally I suggest that you create a seperate php file and put all your functions in there, then reference that file at the top of your scripts. It means a) you know where to find them, b) they then dont bloat your main script and c) you can take that file with you to your next project and have all those useful functions to use straght away.

And yet I still have questions!!!

Okay, here is the query that gives me a number that I want to turn into either Male/Female…


		// Check # of Records Returned.
		if (mysqli_stmt_num_rows($stmt1)==1){
			// Member was Found.

			// Bind result-set to variables.
			mysqli_stmt_bind_result($stmt1, $firstName, $username, $photoName, $photoLabel,
										$gender, $birthYear, $location,
										$occupation, $interests, $aboutMe);

And here is an attempt at my first-ever Function…


	function displayGender($gender){
		if ($gender == 1){
			$gender = 'Male';
		}elseif ($gender == 2){
			$gender = 'Female';
		}else{
			$gender = '';
		}
		
		return $gender;
	}//End of displayGender

Questions:

1.) Will I get into trouble have a variable called $gender in my query-set AND labeling the Function’s Parameter $gender as well?

2.) Do you have any naming convention on this topic?

3.) I purposely used $gender throughout my code, but I am wondering what is a better way to do things?

Or could I get away with what I did?

Personally I suggest that you create a seperate php file and put all your functions in there, then reference that file at the top of your scripts. It means a) you know where to find them, b) they then dont bloat your main script and c) you can take that file with you to your next project and have all those useful functions to use straght away.

I created a directory called utilities and in it a file called functions.php

Thoughts?

Debbie

Nope. Function parameters are also local.

“display” tends to mean you’re going to echo something. “getGender” might be a better name for this function.

Also, if you wanted to distinguish between gender the number and gender the string value, you could name the bound variable $genderId.

You could group all the member data into an array, so you could access it as $member[‘firstName’], $member[‘username’], $member[‘gender’], and so forth. That might reduce variable clutter, and make it easier to pass around all the member data.

And yet I am still in the woods…

I know this is going to sound REALLY stupid, but I’m getting confused what a Function is supposed to return?! :-/

I was under the impression that the proper way to write a Function was to return some value in a variable, and that it was bad to be doing presentational stuff like outputting HTML…

Here is my tweaked Function…


	function getGenderName($gender){
		if ($gender == 1){
			$genderName = 'Male';
		}elseif ($gender == 2){
			$genderName = 'Female';
		}else{
			$genderName = '';
		}

		return $genderName;
	}//End of displayGender

My tiny brain is not getting what is being returned…

To me, it looks like I am returning a VARIABLE which has some value. (Which to me, is a subtle but important difference than just returning a VALUE…)

Back in my regular script, I’m not sure how to use/incorporate my Function?!


	<?php
		echo "<dl>
				<dt>Username:</dt>
				<dd>$username</dd>
				<dt>First Name:</dt>
				<dd>$firstName</dd>
				<dt>Gender:</dt>
				<dd>$gender</dd>

I tried replacing $gender with $genderName, but that didn’t work?! :-/

I also tried putting in getGenderName($gender) but that didn’t work either?! :-/

I’m really getting confused…

Debbie

You do return some value, though it doesn’t need to be in a variable.

You’re not returning the variable itself, you’re returning the value held by that variable.

Yep, that’s true. It’s generally a good idea to keep your logic separate from the presentation.

This one should work. You’ll have to post the full code if we’re going to spot the issue.

If this is my Function…


	function getGenderName($gender){
		if ($gender == 1){
			$genderName = 'Male';
		}elseif ($gender == 2){
			$genderName = 'Female';
		}else{
			$genderName = '';
		}

		return $genderName;
	}//End of displayGender

Can I do this…

$myGender = getGenderName($gender);

Yep, that’s true. It’s generally a good idea to keep your logic separate from the presentation.

Okay.

So what do you do if you have a block of HTML that you need to use in several places?

For instance, I have an “Online Indicator” which is an icon that is either Green, Yellow or Grey depending the Member’s Online Status.

What I wanted to not have to type that code and/or HTML again and again?

This one should work. You’ll have to post the full code if we’re going to spot the issue.

I think I figured it out…

This was NOT working…


	<?php
		echo "<dl>
				<dt>Username:</dt>
				<dd>$username</dd>
				<dt>First Name:</dt>
				<dd>$firstName</dd>
				<dt>Gender:</dt>
				<dd>getGenderName($gender)</dd>
			</dl>";
	?>

But this one does work…


	<?php
		echo "<dl>
				<dt>Username:</dt>
				<dd>$username</dd>
				<dt>First Name:</dt>
				<dd>$firstName</dd>
				<dt>Gender:</dt>
				<dd>" . getGenderName($gender) . "</dd>
			</dl>";
	?>

Is there a proper way to handle if your argument is blank or Null?

I tried using a default value, but that didn’t seem to catch a Null…

Think we’re making some progress on teaching Debbie about Functions?!

Thanks,

Debbie

Yup. The value returned by the function is assigned to your new variable $myGender.

You can put that HTML in a separate file and include it where you need it.

Probably the best option is to not call the function in the first place, especially since you probably wouldn’t want to echo the “<dt>Gender…” either.

if ($gender) {
    echo "<dt>Gender:</dt>
        <dd>" . getGenderName($gender) . "</dd>";
}

And actually, to clean this section up a bit, since what you’re echoing is mostly HTML, I think you should stay in normal HTML most of the time and switch to PHP only when you need to echo something.


<dl>
    <dt>Username:</dt>
    <dd><?php echo $username ?></dd>
    <dt>First Name:</dt>
    <dd><?php echo $firstName ?></dd>
    <?php if ($gender): ?>
        <dt>Gender:</dt>
        <dd><?php echo getGenderName($gender) ?></dd>
    <?php endif ?>
</dl>

If you don’t mind, let me sneak this one in…

Is there a way to do something with the code below so I can more easily refer to it in multiple place…


               // Display Online Status.
               $minutesOnline = (time() - strtotime($lastActivity))/60;

               if ($minutesOnline < 15){
                       // Member Online
                       echo '          <img src="/images/Light_Green_10.png" width="10"
                                                               alt="Member Status: Online"
                                                               title="Green Light." />
                                                               <br />';
               }else if ($minutesOnline < 30){
                       // Member Idle
                       echo '          <img src="/images/Light_Yellow_10.png" width="10"
                                                               alt="Member Status: Idle"
                                                               title="Yellow Light." />
                                                               <br />';
               }else{
                       // Member Offline
                       echo '          <img src="/images/Light_Gray_10.png" width="10"
                                                               alt="Member Status: Offline"
                                                               title="Gray Light." />
                                                               <br />';
               }

I know you shouldn’t put “Presentation” into a Function, but is there still someway that a Function could be used here?

Thanks,

Debbie

I might do it this way.

memberStatus.html.php

<?php if ($minutesOnline < 15): ?>
    <img src="/images/Light_Green_10.png" width="10" alt="Member Status: Online" title="Green Light." /> 
<?php elseif ($minutesOnline < 30): ?>
    <img src="/images/Light_Yellow_10.png" width="10" alt="Member Status: Idle" title="Yellow Light." /> 
<?php else: ?>
    <img src="/images/Light_Gray_10.png" width="10" alt="Member Status: Offline" title="Gray Light." /> 
<?php endif ?>
<br />

Then in your regular page, you could do:

$minutesOnline = (time() - strtotime($lastActivity))/60;
include 'memberStatus.html.php';

and I might do it this way as a function that doesnt output anything to the browser directly. :wink:


function get_memberstatus($minutesOnline){ 
if ($minutesOnline < 15):
    $html ='<img src="/images/Light_Green_10.png" width="10" alt="Member Status: Online" title="Green Light." />'; 
elseif ($minutesOnline < 30): 
    $html ='<img src="/images/Light_Yellow_10.png" width="10" alt="Member Status: Idle" title="Yellow Light." />'; 
else:
    $html ='<img src="/images/Light_Gray_10.png" width="10" alt="Member Status: Offline" title="Gray Light." />'; 
 endif 
return($html);
}

Then in your regular page, you could do:

$minutesOnline = (time() - strtotime($lastActivity))/60;
echo get_memberstatus($minutesOnine);

AS you can see there are many ways to skin that cat !!!

Mandes,

Is it bad to assign HTML to a variable, return it, and then echo it?

Does that violate the “keep presentation out of Functions” rule?

Debbie

I know you addressed Mandes, but I’m already here, so I figured I’d jump in…

Nope.

Not necessarily. The term is “separate logic from presentation,” so as long as the function doesn’t contain complicated application logic, then it should be fine. Also, this is a function that you might want to group separately from your other functions. Instead of putting it in utilities/functions.php, you could put it in… let’s say templates/functions.php.

ASk 10 people and you’ll probably get 10 answers, I definately steer clear of outputing directly to a browser within a function, but if was using your code thoughout my site Id have no qualms about returning the html code PROVIDING that that code was always going to be the same every time. Since you code is only selecting an image and given that that image wont change thoughout your site, IMO youd be OK.

Others may differ … :wink: