- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Functions in PHP
In this part of the PHP programming tutorial, we talk about functions.
A function is a piece of code in a larger program. The function performs a specific task. The advantages of using functions are:
- Reducing duplication of code
- Decomposing complex problems into simpler pieces
- Improving clarity of the code
- Reuse of code
- Information hiding
There are two basic types of functions. Built-in functions and user defined ones. The built-in functions are part of the PHP language. Examples are: phpinfo()
, round()
or abs()
. The user defined functions are created by application programmers to cover their needs. They are created with the function
keyword.
Defining functions
A function is created with the function
keyword.
simple.php
<?php function displayVersion() { echo "this is PHP " . phpversion(); echo "\n"; } displayVersion(); ?>
The function keyword is followed by the function name with round brackets. The body of the function lies between the curly brackets. We say that we call a function. If we call a function, the statements inside the function body are executed.
displayVersion();
This line of the code calls the function.
$ php simple.php this is PHP 5.5.9-1ubuntu4.14
Here we see the outcome of the script.
The return keyword
The return
keyword is used to return a value from the function. A function may or may not return a value.
returning.php
<?php function maximum($x, $y) { if ($x > $y) { return $x; } else { return $y; } } $a = 23; $b = 32; $val = maximum($a, $b); echo "The max of $a and $b is $val \n"; ?>
We have a maximum()
function. It returns a max for two numbers. We could not name it max, because there is already a built-in max()
function. This example was created for learning purposes; we would always prefer the built-in functions in our real-world programs.
if ($x > $y) { return $x; } else { return $y; }
If the $x
variable is greater than $y
, we return $x
. Otherwise we return $y
.
$val = maximum($a, $b);
The value returned by the maximum()
function is assigned to the $val
variable.
echo "The max of $a and $b is $val \n";
We print the max value of the two numbers to the console.
Function arguments
Most functions accept arguments. Arguments are values that are sent to the function. The functions process the values and possibly return some outcome.
fahrenheit.php
<?php function FTC($c) { return $c * 9/5 + 32; } echo FTC(100); echo "\n"; echo FTC(0); echo "\n"; echo FTC(30); echo "\n"; ?>
In our example, we convert Fahrenheit temperature to Celsius. The FTC()
function accepts one argument $c
, which is the Celsius temperature.
$ php fahrenheit.php 212 32 86
Implicit values
The arguments in PHP functions may have implicit values. An implicit value is used if no value is provided.
implicit_value.php
<?php function power($a, $b=2) { if ($b == 2) { return $a * $a; } $value = 1; for ($i = 0; $i < $b; $i++) { $value *= $a; } return $value; } $v1 = power(5); $v2 = power(5, 4); echo "5^2 is $v1 \n"; echo "5^4 is $v2 \n"; ?>
Here we created a power function. The function has one argument with an implicit value. We can call the function with one or two arguments.
$ php implicit_value.php 5^2 is 25 5^4 is 625
Variable number of arguments
A function may accept variable number of arguments. In other words, sometimes we do not know how many arguments will be passed to the function. The func_get_args()
function returns an array comprising a function's argument list.
Since PHP 5.6 there is the ...
operator available to create variadic functions.
variable_arguments1.php
<?php function sum(...$nums) { $sum = 0; foreach ($nums as $n) { $sum += $n; } return $sum; } echo sum(1, 2, 3) . "\n"; echo sum(1, 2, 3, 4) . "\n"; echo sum(1, 2, 3, 4, 5) . "\n"; ?>
We create a sum()
method which can take variable number of arguments. The method calculates the sum of values passed to the method.
$sum = 0; foreach ($args as $n) { $sum += $n; } return $sum;
We calculate and return the sum of the values.
echo sum(1, 2, 3) . "\n"; echo sum(1, 2, 3, 4) . "\n"; echo sum(1, 2, 3, 4, 5) . "\n";
We pass three, four, and five values to the sum()
function.
$ php variable_arguments1.php 6 10 15
This is the output.
variable_arguments2.php
<?php function sum() { $args = func_get_args(); $sum = 0; foreach ($args as $n) { $sum += $n; } return $sum; } echo sum(1, 2, 3) . "\n"; echo sum(1, 2, 3, 4) . "\n"; echo sum(1, 2, 3, 4, 5) . "\n"; ?>
Now the same example is created with the func_get_args()
function.
Static variables
A static variable is a variable that has been allocated statically, whose lifetime extends across the entire run of the program. The default local variables do not retain their value within consecutive calls of the function.
non_static.php
<?php function nonstatic() { $value = 0; $value += 1; return $value; } nonstatic(); nonstatic(); nonstatic(); nonstatic(); echo nonstatic(), "\n"; ?>
In the above example, we have a normal, non-static variable. We increment the variable each time the function is called. We call the function 5 times. However, non-static variables are initiated for each call of the function. After 5 function calls the $value
equals to 2.
The static variables are initiated only once, when the function is first called. They retain their value afterwards.
static.php
<?php function staticfun() { static $value = 0; $value += 1; return $value; } staticfun(); staticfun(); staticfun(); staticfun(); echo staticfun(), "\n"; ?>
After 5 consecutive calls, the $value
is equal to 5.
$ php nonstatic.php 2 $ php static.php 6
Anonymous functions
Anonymous functions do not have a name.
anonymous.php
<?php $var = function() { echo "This is anonymous function\n"; }; $var(); ?>
We assign a function body to a variable. It is possible to call the function only via this variable.
$var = function() { echo "This is anonymous function\n"; };
Notice the semicolon after the closing curly bracket. It is required because the construct is an assignment.
$ php anonymous.php This is anonymous function
This is the output of the example.
Passing arguments by value and by reference
PHP supports two ways of passing arguments to functions. The default way is passing arguments by value. When we pass arguments by value, the function works only with the copies of the values. This may lead to performance overheads when we work with large amounts of data.
When we pass values by reference, the function receives a reference to the actual value. The original values are affected when modified. This way of passing values is more time and space efficient. On the other hand, it is more error prone.
Which way of passing arguments should we use? It depends on the situation. Say we have a set of data, salaries of employees. If we want to compute some statistics of the data, we do not need to modify them. We pass by values. If we work with large amounts of data and the speed of computation is critical, we pass by reference. If we want to modify the data, e.g. do some reductions or raises to the salaries, we might pass by reference.
The following two examples cover both concepts.
swap1.php
<?php function swap($a, $b) { $temp = $a; $a = $b; $b = $temp; echo "inside swap function:\n"; echo "\$a is $a \n"; echo "\$b is $b \n"; } $a = 4; $b = 7; echo "outside swap function:\n"; echo "\$a is $a \n"; echo "\$b is $b \n"; swap($a, $b); echo "outside swap function:\n"; echo "\$a is $a \n"; echo "\$b is $b \n"; ?>
The swap function swaps the numbers between the $a
and $b
variables. The original variables are not affected.
$a = 4; $b = 7;
At the beginning, these two variables are initiated.
swap($a, $b);
We call the swap()
function. The function takes $a
and $b
variables as parameters.
$temp = $a; $a = $b; $b = $temp;
Inside the swap()
function, we change the values. Note that the $a
and $b
variables are defined locally. They are valid only inside the swap()
function.
$ php swap1.php outside swap function: $a is 4 $b is 7 inside swap function: $a is 7 $b is 4 outside swap function: $a is 4 $b is 7
The output shows that the original variables were not affected.
The next code example passes values to the function by reference. The original variables are changed inside the swap()
function.
swap2.php
<?php function swap(&$a, &$b) { $temp = $a; $a = $b; $b = $temp; echo "Inside the swap function:\n"; echo "\$a is $a \n"; echo "\$b is $b \n"; } $a = 4; $b = 7; echo "Outside the swap function:\n"; echo "\$a is $a \n"; echo "\$b is $b \n"; swap($a, $b); echo "Outside the swap function:\n"; echo "\$a is $a \n"; echo "\$b is $b \n"; ?>
We use the &
character to pass values by reference.
function swap(&$a, &$b) { ... }
The example is almost identical to the previous one. Except for the ampersand characters.
$ php swap2.php Outside the swap function: $a is 4 $b is 7 Inside the swap function: $a is 7 $b is 4 Outside the swap function: $a is 7 $b is 4
Here we see that the swap()
function really changed the values of the variables.
Recursion
Recursion, in mathematics and computer science, is a method of defining functions in which the function being defined is applied within its own definition. In other words, a recursive function calls itself to do its job. Recursion is an alternative to iteration. Recursion is the main approach in functional languages.
A typical example is the calculation of the factorial.
recursion.php
<?php function factorial($n) { if ($n==0) { return 1; } else { return $n * factorial($n - 1); } } echo factorial(4), "\n"; echo factorial(10), "\n"; ?>
In this code example, we calculate the factorial of two numbers.
return $n * factorial($n - 1);
Inside the body of the factorial function, we call the factorial function with a modified argument. The function calls itself.
$ php recursion.php 24 3628800
These are the results.
Global and local variables
Next we will talk about the scope of the variables in PHP. A scope is the range in which a variable can be referenced. When we work with functions, there are two basic scopes: the global and the local scope. The local scope is also called a function scope.
scope1.php
<?php $value = 1; function simple() { var_dump($value); } simple(); ?>
A variable defined outside a function body cannot be referenced within a function.
$ php scope1.php PHP Notice: Undefined variable: value in /home/janbodnar/prog/php/functions/scope1.php on line 7 NULL
The $value
variable is NULL in the simple()
function.
scope2.php
<?php $value = 4; function simple() { $value = 3; echo $value, "\n"; } simple(); echo $value, "\n"; ?>
In this example, we have two variables with the same name. They do not collide because they exist in different scopes.
$ php scope2.php 3 4
The value is 3 inside the function and 4 outside the function.
In the next example, we will modify a value inside the function.
scope3.php
<?php $value = 1; function simple() { global $value; $value = 2; } echo $value, "\n"; simple(); echo $value, "\n"; ?>
We use the global
keyword to reference a variable defined outside the body of the function.
$ php scope3.php 1 2
The $value
was successfully modified inside the simple()
function.
In this part of the PHP tutorial, we covered PHP functions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论