Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index

PHP Script Tips - Creating Your Own Functions

By: FYICenter.com

Part:   1  2  3  4  5  

(Continued from previous part...)

How To Return a Reference from a Function?

To return a reference from a function, you need to:

  • Add the reference operator "&" when defining the function.
  • Add the reference operator "&" when invoking the function.

Here is a PHP script on how to return a reference from a function:

<?php
$favor = "vbulletin";
function &getFavorRef() {
  global $favor;
  return $favor;
}
$myFavor = &getFavorRef();
print("Favorite tool: $myFavor\n");
$favor = "phpbb";
print("Favorite tool: $myFavor\n");
?>

This script will print:

Favorite tool: vbulletin
Favorite tool: phpbb

As you can see, changing the value in $favor does affect $myFavor, because $myFavor is a reference to $favor.

How To Specify Argument Default Values?

If you want to allow the caller to skip an argument when calling a function, you can define the argument with a default value when defining the function. Adding a default value to an argument can be done like this "function name($arg=expression){}. Here is a PHP script on how to specify default values to arguments:

<?php
function printKey($key="download") {
  print("PHP $key\n");
}
printKey();
printKey("hosting");
print("\n");
?>

This script will print:

PHP download
PHP hosting

How To Define a Function with Any Number of Arguments?

If you want to define a function with any number of arguments, you need to:

  • Declare the function with no argument.
  • Call func_num_args() in the function to get the number of the arguments.
  • Call func_get_args() in the function to get all the arguments in an array.

Here is a PHP script on how to handle any number of arguments:

<?php
function myAverage() {
  $count = func_num_args();
  $args = func_get_args();
  $sum = array_sum($args);
  return $sum/$count;  
}
$average = myAverage(102, 121, 105);
print("Average 1: $average\n");
$average = myAverage(102, 121, 105, 99, 101, 110, 116, 101, 114);
print("Average 2: $average\n");
?>

This script will print:

Average 1: 109.33333333333
Average 2: 107.66666666667

Part:   1  2  3  4  5  


Selected Developer Jobs:

More...