PHP Introduction | Structure and Object Orientation | Structuring with Functions
What determines a programmer’s level? In practice, it can be said to be “scale.” An amateur may be able to write a program of about 100 lines, but a beginner cannot write a 1,000-line program. A 10,000-line program is difficult unless you are a professional. This comes before whether the functions used are difficult or the algorithm is complex. The problem is how well you can design a large program so that it is neatly organized and understandable.
A 100-line program can be made just by writing statements in order. In PHP, submitting several forms can quickly produce that much code. However, a 1,000-line program cannot be made that way. You must properly design a structure that organizes the program by role and calls the necessary processing when needed. This is the idea of “structuring.”
In PHP, the first step in structuring is the “function.” By organizing scripts that were written in a long sequence, separating parts, and defining them as functions, you can design the whole program cleanly and clearly. This is the first step toward writing larger programs.
Functions such as echo, implode/explode, and fopen/fclose have appeared so far. In PHP, the basic features are all defined as functions. But functions are not only those prepared in PHP itself. Developers can also define their own functions by writing scripts. A function is defined as follows.
function functionName(parameter1, parameter2, ...) {
...... write the processing to perform here ......
...... if returning a result, return it at the end ......
}
When creating a function, think about “arguments” and “return values.” An argument is a value passed when calling a function. For example, when calling a function like fopen("data.txt");, you put the necessary value in parentheses. That is an argument.
When defining your own function, think about what values the function needs and specify them as arguments. In the function’s parentheses, write variables that receive the passed values. These are called parameters. When the function is called, the values specified as arguments are assigned to these parameter variables. After that, you can use the passed argument values through these variables.
A return value sends the result of the function back to the caller. Write the value to return in the form return value;. return exits the function and returns the specified value to the caller. Since it exits the processing, anything after return is not executed.
Let us actually use a function. First, before using a function, here is the source code.
<?php
if ($_POST != null) {
$str = $_POST['text1'];
$str = htmlspecialchars(strtoupper($str));
$result = str_replace('PHP', '<b>PHP</b>', $str);
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>sample page</title>
</head>
<body>
<h1>Hello PHP!</h1>
<p><?php echo $result; ?></p>
<hr>
<p>Please write a sentence that includes the text PHP here.</p>
<form method="post" action="./index.php">
<textarea name="text1" cols="40" rows="5"><?php echo $str; ?></textarea>
<br><input type="submit">
</form>
<hr>
</body>
</html>
When text is submitted here, every occurrence of the text “PHP” is displayed in bold. This is a simple example that replaces submitted text with the str_replace function. The submitted text is also processed by a function called strtoupper, which converts alphabetic text to uppercase and returns it.
Benefits of Functions
Now let us write the example by structuring it with a function, although that may sound more impressive than it is. The source code is as follows.
<?php
function getBoldStr($str) {
$str = htmlspecialchars(strtoupper($str));
$res = str_replace('PHP', '<span style="font-weight:bold;color:red">PHP</span>', $str);
return $res;
}
if ($_POST != null) {
$str = $_POST['text1'];
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>sample page</title>
</head>
<body>
<h1><?php echo getBoldStr("Hello PHP!"); ?></h1>
<p><?php echo getBoldStr($str); ?></p>
<hr>
<p><?php echo getBoldStr("Please write a sentence that includes the text PHP here."); ?></p>
<form method="post" action="./index.php">
<textarea name="text1" cols="40" rows="5"><?php echo $str; ?></textarea>
<br><input type="submit">
</form>
<hr>
</body>
</html>
This time, PHP is shown in bold and red so that the converted parts are easier to see. Let us look at the difference.
At the beginning, a function named function getBoldStr($str) is defined. It prepares one parameter, $str. The text in $str is replaced, and the completed result is returned with return. Looking at the call site, it is written like this.
<?php echo getBoldStr($str); ?>
The required value is passed in parentheses after getBoldStr. You can see that its usage is no different from ordinary functions provided by PHP.
By turning the processing into a function, it can now be called from anywhere in the program. Here, not only the submitted text display but also the heading and explanatory text are all processed and output by this function. Because the processing has been made into a function, you no longer need to write the same process many times. Whenever it is needed, you call it and it performs the required work. This is the benefit of using functions.
Variable Scope
If you look closely at this script, you will notice something interesting about variables. The variable $str is used both as a function parameter and elsewhere. Is there no concern that using the same variable like this will overwrite or change values unexpectedly? In fact, $str inside the function and $str outside the function are different variables.
Variables have a defined range in which they can be used. This is called “scope.” When a variable is used inside a function, that variable can be used only inside the function. At the moment the function exits, the variable disappears. Even if the function is called again, the variables from the previous call are gone, and everything is newly created.
Therefore, variables created inside a function and used only there are called “local variables.” By contrast, variables created outside functions and usable across the whole script are called “global variables.” When using functions, you need to understand this “variable scope” well.