Function Arguments in PHP

This tutorial explains how to use function arguments in PHP.

1410 views

Edited: 2018-01-20 16:56

Function Arguments can be used to pass information to functions, which will then be handled or acted upon by the code within the function.

If the function is contained within a class, the choice is often between using class variables (properties) or function arguments. It can often be a better solution to use properties, since the data to be passed to the functions will often also be used by other functions. It is also harder to call a function (method) that has arguments, then a calling a fonction that simply uses the properties of a class.

Single Argument

To pass something on to a function, use the below:

function ContentAd($Arg){
// validation

echo '<div class="Advertisement">'. $Arg .'</div>';

}

The $Arg variable, will contain the content, of whatever you pass on to the function.

These Arguments allow you to do many different things, one example would be, to take user submitted links, and inclose them properly in anchor tags.

<?php
  // First define the Function
function ContentAd($Arg){
// validation

echo '<div class="Advertisement">' . $Arg . '</div>';

}
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">

  <head>
  <title>My first Website</title>

  </head>

  <body>
<?php
  // Then call the Function somewhere else in the Script.

  $content = '<a href="http://Beamtic.com/">Beamtic Tutorials</a>';

  ContentAd($content);

?>
  </body>

</html>

The above would still output the same, but this time the link was passed on to the function.

Multiple Arguments

You can use multiple arguments by separating them with a comma (,).

function ContentAd($Arg1, $Arg2){
// validation

echo '<div class="Advertisement">'. $Arg1 .' - '. $Arg2 .'</div>';

}

Comma is also used when calling the Function.

ContentAd($etc1, $etc2);

Strings and integers

You can also use Strings and integers as arguments, an example is shown below.

ContentAd('String', 144);

Video

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials