Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP Functions

PHP Functions


The true power of PHP comes from its functions.

PHP provides over 1000 built-in functions.


PHP Built-in Functions

To view the complete reference manual and examples for all array functions, please visit our PHP Reference Manual.


PHP Functions

In this chapter, we will explain how to create your own functions.

If you want a script to execute when the page loads, you can put it inside a function.

A function is executed by calling it.

You can call a function anywhere on the page.


Creating a PHP Function

A function is executed by calling it.

Syntax

PHP function guidelines:

Example

A simple function that outputs my name when called:

Example

Output:



My name is Kai Jim Refsnes


PHP Functions - Adding Parameters

To add more functionality to a function, we can add parameters, which are similar to variables.

Parameters are specified in parentheses after the function name.

Example 1

The example below will output different first names but the same last name:

Example

" ; } echo " My name is " ; writeName ( " Kai Jim " ); echo " My sister's name is " ; writeName ( " Hege " ); echo " My brother's name is " ; writeName ( " Stale " ); ?>

Output:



My name is Kai Jim Refsnes.

My sister's name is Hege Refsnes.

My brother's name is Stale Refsnes.

Example 2

The function below has two parameters:

Example

" ; } echo " My name is " ; writeName ( " Kai Jim " , " . " ); echo " My sister's name is " ; writeName ( " Hege " , " ! " ); echo " My brother's name is " ; writeName ( " Ståle " , " ? " ); ?>

Output:

My name is Kai Jim Refsnes.

My sister's name is Hege Refsnes!

My brother's name is Ståle Refsnes?


PHP Functions - Return Values

To make a function return a value, use the return statement.

Example

Output:



1 + 16 = 17


PHP Variable Functions

Variable functions refer to functions in PHP where a variable is used as the function name to be called.

Variable functions allow us to dynamically decide which function to call at runtime.

Example

\n" ; } function bar ( $arg = '' ) {     echo "In bar(); argument was '$arg'.
\n" ; } // wrapper function using echo function echoit ( $string ) { echo $string ; } $func = 'foo' ; $func ( ) ; // call foo() $func = 'bar' ; $func ( 'test' ) ; // call bar() $func = 'echoit' ; $func ( 'test' ) ; // call echoit() ?>

You can also use variable function syntax to call an object's method.

Example

$name ( ) ; // call Bar() method } function Bar ( ) { echo "This is Bar" ; } } $foo = new Foo ( ) ; $funcname = "Variable" ; $foo -> $funcname ( ) ; // call $foo->Variable() ?>