Jump to content

Functions


master82

Recommended Posts

The point of a function is to wrap some lines of code that you plan on using more than once into a single package.  This way if you need to change that code, you only have to do it once, rather than digging through all of your lines of code to find every instance.

For example:

[code]function foo($arg1) {
  echo $arg1;
}[/code]

Very simple function, just echo's out what it is passed.  You could use that function to output all of your data to the browser, for example.  Now, if you weren't using that function, and you wanted to make all text output to the user red, you would have to dig through your code and put a style tag around each one.  But with the function it's as easy as:

[code]function foo($arg1) {
  echo '<span style="color: red;">' . $arg1 . '</span>';
}[/code]

And now all text will be red.
Link to comment
https://forums.phpfreaks.com/topic/17422-functions/#findComment-74160
Share on other sites

Generally, the purpose of a function is to prevent the repetition of code.  You create a function to perform  certain task that could be extremely inefficient to type out over and over again.  where a simple example of a function would be to add 1 to a number,

function addone($number)
{
    $number++;
}

This could be called like '$newnumber = addone($oldnumber)', which is actually less efficient to type thatn $oldnumber++...howver, it illustrates the use of a function.  Now, consider having to echo a large amount of HTML, this could exceed 200 lines.  Say, for example, you needed to show this HTML whenever a user-error occured (e.g. they didn't fill in a field in a form, they chose an incorrect answer in a quiz).  Now, without functions, for every error that occured, you would have to copy and paste the echo statement for every error.  This means your code could easily exceed 1,000 lines.  Now, consider this with functions.  You declare the function, in which you have the echo statement, then you just call the function ater every error.  this means, instead of 200 lines of code for every error, there is potentially just one.

Also, assume you made an error in the echo statement, if you had copied and pasted the statement, you would have to ammend the statement for each error.  If you used a single function, you would need to edit this once.
Link to comment
https://forums.phpfreaks.com/topic/17422-functions/#findComment-74213
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

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.