PHP

PHP Functions and Arguments

 

 

In the previous two sections, you saw how to set
up your own functions, and the importance of Scope. In particular, you learnt
that you need a handy way to pass values to your function. That’s where arguments
come in.

 

Arguments

Functions can be handed variables, so that you can do something with what’s
inside of them. You pass the variable over to your functions by typing them
inside of the round brackets of the function name. Here’s a script similar
to the one you saw earlier:

<?PHP

$error_text = “Error message”;
display_error_message($error_text);

function display_error_message($error_text) {

print $error_text;

}

?>

The only difference is the that we now have something between the round brackets
of our function:

function display_error_message($error_text)
{

}

The name is the same, but we’ve put a variable in between the round brackets.
This is the variable that we want to do something with. The one called $error_text.
By typing a variable inside of the round brackets, you are setting up something
called an argument. An argument is a variable or value that you want
your function to deal with.

Notice how the function is called:

$error_text = “Error message”;
display_error_message($error_text);

The first line puts something into the variable. But when you want to hand
something to a function that has an argument, you need to type it between
the round brackets of the function call. In our script, we’re typing the name
of the variable. But this would do just as well:

display_error_message(“Error message”);

Here, we’re putting direct text between the round brackets. That works ok.
But try it like this:

$error_text = “Error message”;
display_error_message( );

You’ll get an error message from PHP. Something like this:

“Warning: Missing argument 1 for display_error_message(
)”

That’s telling you that your function has been set up to take an argument,
but that you’ve left the round brackets empty when you tried to call the function.

Your functions can have more than 1 argument. Just separate each argument
with a comma. Like this:

function error_check($error_text, error_flag)
{

}

To call this function, you’d then need to hand it two arguments:

$error_text = “Error message”;
error_flag = 1;

error_check($error_text, error_flag);

If you only hand the above function 1 argument, you’d get error messages
from PHP.

So, to recap:

  • To pass something to a function, create an argument
  • To call a function that has an argument, don’t leave
    the round brackets empty

In the next part, you’ll see a function that checks for blank text boxes.
The function has 1 argument.

|

Kaynak : https://www.homeandlearn.co.uk/php/php8p3.html ‘sitesinden alıntı

Yorum Yap