PHP Functions

kane

194.***.***.***
1,451 days ago

PHP Functions

Create a PHP Function

A function is a block of code that can be executed whenever we need it.

Creating PHP functions:

* All functions start with the word "function()"
* Name the function - It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number)
* Add a "{" - The function code starts after the opening curly brace
* Insert the function code
* Add a "}" - The function is finished by a closing curly brace

Example

A simple function that writes my name when it is called:

Code:


<html>
<body>

<?php
function writeMyName()
{
echo "Kai Jim Refsnes";
}

writeMyName();
?>

</body>
</html>



Use a PHP Function

Now we will use the function in a PHP script:

Code:

<html>
<body>

<?php
function writeMyName()
{
echo "Kai Jim Refsnes";
}

echo "Hello world!<br />";
echo "My name is ";
writeMyName();
echo ".<br />That's right, ";
writeMyName();
echo " is my name.";
?>

</body>
</html>



The output of the code above will be:

Code:

Hello world!
My name is Kane Dixon.
That's right, Kane Dixon is my name.

penguinmama

12.***.***.***
1,442 days ago
Well, not exactly (hehehehe)... the output would actually be:

Code:


Hello world!
My name is Kai Jim Refsnes..
That's right, Kai Jim Refsnes is my name.



:D