Function Arguments in PHP
This tutorial explains how to use function arguments in PHP.
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);
Tell us what you think: