Advertisement:

Author Topic: PHP Lesson 13 - creating custom functions (one of many examples to come)  (Read 24161 times)

Offline Parham

  • SMF Friend
  • Sophist Member
  • *
  • Posts: 1,317
  • Gender: Male
  • #!/usr/bin/perl
    • Online Node
By now, you should have yourself familiarized with the built-in PHP functions, if you don't, please go back and review them.  Again, the functions are located at http://www.php.net/quickref.php and you are encouraged to read through them and get yourself familiar with the many different actions you can perform with them.

One of the many functions in the PHP documentation is array_sum().  array_sum()'s documentation can be found at http://www.php.net/manual/en/function.array-sum.php.  What does array_sum() do?  It simply adds up all the number types in an array and returns the sum.  You should know how to use this function (from reading the documentation):

Code: [Select]
<?
$array = array(1,5.5,2.0,3,6,1);
echo array_sum($array); //prints "18.5"
?>

This is a clear example of what a function is there to do.  This function does a specific task and it saves us from having to repeat code (possibly from summing up several arrays).  Our task for this lesson is the create a NEW function which performs the exact same function as array_sum().  This will help us learn how to implement our own custom functions and also give us a better understanding of why we create functions.

The basic syntax of a function is the following:

function function_name($parameter_1,$parameter_2...$parameter_n) {
//do something with the parameters
//create a new variable ($variable)
return $variable
}

In case you're curious, this is what return does:  When you do "$variable = array_sum($array)", array_sum itself uses the "return" statement which returns a value which in turn you assign to $variable.

Because we want to keep this as simple as possible, we're going to go about making our function with the assumption that the contents of the array will always only be number types.  The first thing we want to do is create the body of our function.  What does this mean?  This means that if we had a variable (or variables), how would we go about doing the job we want to do?

So let's say we have our variable $array (of array type), and it contains numbers.  How do we go about adding all the numbers?

Code: [Select]
$variable = 0; //create our new variable to store the sum
foreach ($array as $element) { //pretend as if you already have $array
$variable += $element; //add the element to the variable holding the sum
}

We're already half way done; we've created the body of our function.  Let's give our function a name now.  In PHP, you cannot name functions which are built into PHP, or else you'll get an error stating you can redeclare the function.  Since the function we're duplicating is called array_sum(), we'll call our function array_sum_copy().  What variable(s) does our function need as input to do its job?  Well, above, we created the body of our code under the impression that an array ($array) was declared, so that is what we'll need as input.  Finally, what output does our function return?  Well, we know that the body of our function stores the sum of the array elements inside $variable, so that's what we'll want to return to the user of the function (using the "return" statement).

Now all we have to do is put our function together:

Code: [Select]
function array_sum_copy($array) {
  $variable = 0;
  foreach ($array as $element) { //pretend as if you already have $array
    $variable += $element;
  }
  return $variable;
}

Let's go back and once again look at what we did.  We selected a name for our function.  We found out what variables our function will need to work (the parameters).  We created the body of our function and used all the parameters of the function.  Finally we figured out what output we want to return and we used the "return" statement to return it.

And this is how it would look if we used it:

Code: [Select]
<?

$array = array(1,5.5,2.0,3,6,1);
echo array_sum_copy($array); //prints "18.5"

function array_sum_copy($array) {
  $variable = 0;
  foreach ($array as $element) { //pretend as if you already have $array
    $variable += $element;
  }
  return $variable;
}

?>

I will be doing one more of these in a few lessons, but I want to just note on a few things.  First, you can create a function that has SEVERAL parameters.  Second, a function can return SEVERAL values (this will be demonstrated later).  Finally, variables declared in a function will only exist in that function.  For example, we declared $variable to hold the sum of the array elements, but $variable will only exist within the block it was declared, nowhere else (unless otherwise stated).  This is where we get into scope, and I will be explaining how scope works in PHP in the next lesson.

Offline [Unknown]

  • SMF Friend
  • SMF Master
  • *
  • Posts: 36,102
  • Gender: Male
Re:PHP Lesson 13 - creating custom functions (one of many examples to come)
« Reply #1 on: September 19, 2003, 12:37:08 AM »
*cough* Actually, array_sum is/should be written in C++, and it uses a Zend engine macro to return it's variable... although I suppose that doesn't matter overly..

And... isn't scope a wonderful thing?  It saves memory and everything 8).

-[Unknown]

Offline Parham

  • SMF Friend
  • Sophist Member
  • *
  • Posts: 1,317
  • Gender: Male
  • #!/usr/bin/perl
    • Online Node
Re:PHP Lesson 13 - creating custom functions (one of many examples to come)
« Reply #2 on: September 19, 2003, 12:44:15 AM »
*cough* Actually, array_sum is/should be written in C++, and it uses a Zend engine macro to return it's variable... although I suppose that doesn't matter overly..

And... isn't scope a wonderful thing?  It saves memory and everything 8).

-[Unknown]

scope IS a great thing :D.  It was probably a bad idea to reimplement an already existing PHP function, but it was also the easiest way to show how to create a custom function (because we already knew the expected outcome, the input, and how to create the body)

Offline pulpitfire

  • Sophist Member
  • *****
  • Posts: 1,132
  • Gender: Male
  • This is what the php parser looks like.
    • Pulpitfire Devotionals
Re: PHP Lesson 13 - creating custom functions (one of many examples to come)
« Reply #3 on: November 18, 2003, 10:15:05 AM »
I think it would be cool and useful to use examples from YaBB SE or SMF code as well.  That way, it would help people understand their forum, and how to mod it (e.g. Index.php has a good example of the array function.).

Offline [Unknown]

  • SMF Friend
  • SMF Master
  • *
  • Posts: 36,102
  • Gender: Male
Re: PHP Lesson 13 - creating custom functions (one of many examples to come)
« Reply #4 on: November 18, 2003, 06:18:59 PM »
Actually, array is *not* a function.  It's what is called a "language construct".  The difference between language contructs and functions is that language contructs often do things functions can't, and are almost always faster.

For example, this:
if ($test == 0 || $test == '')

Seems like a great way to check if $test is '' or 0, right?  But, if you use the language contruct empty, it will be just a tad faster, and in my opinion more readable:

if (empty($test))

This will also check if $test isn't even defined.  (!isset($test))

Another language contruct is... if.  Yeah, if is a language contruct.  It helps you "construct' code, if that helps.  You'll notice that if treats the code following it differently than a function could.  This is what I meant by language contructs being able to do things functions cannot.

Sadly enough, PHP and most other languages do not allow you to create your own language contructs.  That's what the language part is supposed to mean - they are part of the language.

-[Unknown]

Offline adam

  • Semi-Newbie
  • *
  • Posts: 97
  • Gender: Male
    • The Daily Blogger
Re: PHP Lesson 13 - creating custom functions (one of many examples to come)
« Reply #5 on: October 17, 2004, 09:00:50 PM »
Also, variables that get created in functions can only stay in functions.  You can print out a variable from a function outside the function.

Offline [Unknown]

  • SMF Friend
  • SMF Master
  • *
  • Posts: 36,102
  • Gender: Male
Re: PHP Lesson 13 - creating custom functions (one of many examples to come)
« Reply #6 on: October 17, 2004, 09:25:39 PM »
Also, variables that get created in functions can only stay in functions.  You can print out a variable from a function outside the function.

This is called variable scope.  That is, where the variable is "important".  There are two pertinent kinds of scope:

  - local scope: this is the scope inside functions, etc.  It means "local" to that function.
  - global scope: this is outside functions.  Things can be "extracted" from the global scope into the local scope.

Additionally, there are things called "superglobals" these are variables that are so important that they are in every scope.

To extract a variable from the global scope, use the global construct:

global $xyz;

From then on, if you change $xyz, the global variable $xyz will also be changed.  You can also use the superglobal $GLOBALS to access the global scope from any scope - in this case, you might use:

$GLOBALS['xyz'] = 4;

In this case, $GLOBALS is simply an associative array of all the variables in the global scope.... not so bad, eh?

-[Unknown]

Offline adam

  • Semi-Newbie
  • *
  • Posts: 97
  • Gender: Male
    • The Daily Blogger
Re: PHP Lesson 13 - creating custom functions (one of many examples to come)
« Reply #7 on: October 17, 2004, 09:54:09 PM »
Yeah unknown I just figured that out after reading the tut about it here.   :)  This is another thing I gotta build upon.  I have never created a function.