Php function name syntax

PHP Functions

PHP has thousands of built-in functions. Each of those functions is focused to perform a specific task. We have already discussed some of them.

  • echo() — to output a string
  • define() — to define a constant
  • var_dump() — to dump data of a variable

You will learn about the other built-in functions step-by-step in this tutorial.

PHP User-Defined Functions

The function declaration starts with the function keyword. Then, the function name and arguments.

function functionName(arg1, arg2, . ) < code to be executed >

PHP Naming User-Defined Functions

Function naming is almost the same as variable naming except for the $ sign at the beginning. Functions do not have the $ sign.

  • A function name should start with a letter or underscore.
  • A function name cannot start with a number.
  • Letters, numbers, and underscores can be used after the first letter in a function.
  • A function name is case-insensitive (Both boom() and Boom() refers to the same function.)
  • Tip: Always name functions with a name that describes the usage of the function.
Читайте также:  Http moodle dahluniver ru mod quiz processattempt php

PHP Declaring User-Defined Functions

Let’s create our first function.

  • First, we declare the function greet() using the function syntax.
  • The block of code inside the curly braces ( <> ) is the function code. This code is executed when we call the function.
  • Then, we call our function using its name and parentheses: greet();

Note: In PHP, parentheses are used to call a function.

PHP User-Defined Function Example

  else if ($hour < 17) < echo 'Good Afternoon'; >else < echo 'Good Night'; >> greet(); // calling the function 

PHP Function Arguments

Function arguments are the values passed into a function. An argument is a variable inside the function.

  • Arguments are defined inside the parentheses which are there immediately after the function name.
  • A function can have any number of arguments, separated them with commas.
  • An argument name should obey the same rules as a variable since arguments are variables.
  • First, we declare a function named myName with one argument, $name .
  • Then, we call the function several times with different argument values.
  • Note the value inside the parentheses of the function call. That value is assigned to $name when the function executes.

PHP Function Arguments Example

 '; // line break > myName('Joe'); myName('Adam'); myName('David'); 

Functions can have multiple arguments.

PHP Function Multiple Arguments Example

  My age is $age 
My country is $country

"; > myDetails('Joe', 22, 'USA'); myDetails('Adam', 25, 'United Kingdom'); myDetails('David', 30, 'France');

PHP Function Arguments — Passing By Reference

By default, arguments are passed into functions by value. See the following example to understand it.

PHP Passing Arguments By Value Example

 '; // outputs "Hyvor Developer" > $rootName = 'Hyvor'; changeName($rootName); echo 'Outside the function: ' . $rootName; // it is stil 'Hyvor' 
  • $rootName variable is set to «Hyvor».
  • Then, it is passed into changeName() function as the $name argument.
  • Inside the function, «Hyvor» is changed to «Hyvor Developer».
  • But, after executing the function the global variable $rootName still holds the value «Hyvor».

You can change a variable from a function by passing it into the function by reference. Just prepend an & sign to the argument name in the function definition.

PHP Passing Arguments By Reference Example

 '; // outputs "Hyvor Developer" > $rootName = 'Hyvor'; changeName($rootName); echo 'Outside the function: ' . $rootName; // now it's 'Hyvor Developer' 

PHP Function Arguments — Default Values

To specify a default value for an argument, just assign that with the basic assignment operator ( = ) in the function definition. If the argument is not provided when calling the function, this default value is used.

PHP Functions — Default Values for Arguments Example

 "; > printNumber(2); printNumber(25); printNumber(); // will print 10, the default value printNumber(500); 

PHP Function Arguments — Type Declaration

Type declaration (also known as type hinting) can be used to specify a data type for each argument. PHP will throw an error on incorrect data types. The data type should be added before the argument to specify type declaration for it.

PHP Functions — Type Declaration in Arguments

  My age is $age 
My country is $country

"; > myDetails('Joe', 22, 'USA'); myDetails('Adam', 25, 'United Kingdom'); myDetails('David', 30, 'France'); # myDetails('John', 'N/A', 'Australia'); this will cause an error

Valid Types For Type Declaration

Type Description Min PHP Version
array The argument must be an array 5.1.0 Run Example ››
callable The argument must be a callable (function or method) 5.4.0 Run Example ››
int The argument must be an integer 7.0.0 Run Example ››
float The argument must be a float 7.0.0 Run Example ››
bool The argument must be a boolean 7.0.0 Run Example ››
string The argument must be a string 7.0.0 Run Example ››

PHP Functions — Returning

There are two uses of return statements.

  • To return a value from a function.
  • To stop the execution of a function when a certain condition is true.

PHP Functions — Returning Values

PHP Functions — Returning Values Example

  echo '5 + 5 = ' . sum(5,5) . '
'; echo '4 + 3 = ' . sum(4,3) . '
'; echo '8 + 1 = ' . sum(8,1) . '
';

PHP Functions — Type Declaration for Returning Values

The types are as same as the types in argument type declaration. The type should be specified after the function name, adding a semicolon : .

PHP Functions — Returning Values of a Specific Data Type

  var_dump(sum(5, 2)); // float value is returned 

The above function should return a float. Otherwise PHP will cast it to float if possible. For example, if the result is an integer, it will be casted into float and then returned. But, if you return a string, PHP will throw an error.

PHP Variable Functions

If a variable which contains a string has parentheses appended to it, PHP checks for a function with the same name, and will execute it. This concept is called variable functions.

PHP Variable Functions Example

  $functionName = 'printSentence'; $functionName(); // called printSentence function 

PHP Anonymous Functions

Functions without a name are called anonymous functions (or closures). They are really helpful to send callback arguments into functions.

PHP Anonymous Functions Example

In the above example, we specify the first parameter of callFunc() function as an anonymous function.

True, this can be tricky for you. We will use anonymous functions with more examples in the later chapters.

Источник

PHP Functions

PHP has more than 1000 built-in functions, and in addition you can create your own custom functions.

PHP Built-in Functions

PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a specific task.

Please check out our PHP reference for a complete overview of the PHP built-in functions.

PHP User Defined Functions

Besides the built-in PHP functions, it is possible to create your own functions.

  • A function is a block of statements that can be used repeatedly in a program.
  • A function will not execute automatically when a page loads.
  • A function will be executed by a call to the function.

Create a User Defined Function in PHP

A user-defined function declaration starts with the word function :

Syntax

Note: A function name must start with a letter or an underscore. Function names are NOT case-sensitive.

Tip: Give the function a name that reflects what the function does!

In the example below, we create a function named «writeMsg()». The opening curly brace ( < ) indicates the beginning of the function code, and the closing curly brace ( >) indicates the end of the function. The function outputs «Hello world!». To call the function, just write its name followed by brackets ():

Example

writeMsg(); // call the function
?>

PHP Function Arguments

Information can be passed to functions through arguments. An argument is just like a variable.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument ($fname). When the familyName() function is called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs several different first names, but an equal last name:

Example

familyName(«Jani»);
familyName(«Hege»);
familyName(«Stale»);
familyName(«Kai Jim»);
familyName(«Borge»);
?>

The following example has a function with two arguments ($fname and $year):

Example

function familyName($fname, $year) echo «$fname Refsnes. Born in $year
«;
>

familyName(«Hege», «1975»);
familyName(«Stale», «1978»);
familyName(«Kai Jim», «1983»);
?>

PHP is a Loosely Typed Language

In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.

In PHP 7, type declarations were added. This gives us an option to specify the expected data type when declaring a function, and by adding the strict declaration, it will throw a «Fatal Error» if the data type mismatches.

In the following example we try to send both a number and a string to the function without using strict :

Example

function addNumbers(int $a, int $b) return $a + $b;
>
echo addNumbers(5, «5 days»);
// since strict is NOT enabled «5 days» is changed to int(5), and it will return 10
?>

To specify strict we need to set declare(strict_types=1); . This must be on the very first line of the PHP file.

In the following example we try to send both a number and a string to the function, but here we have added the strict declaration:

Example

function addNumbers(int $a, int $b) return $a + $b;
>
echo addNumbers(5, «5 days»);
// since strict is enabled and «5 days» is not an integer, an error will be thrown
?>

The strict declaration forces things to be used in the intended way.

PHP Default Argument Value

The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument:

Example

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>

PHP Functions — Returning values

To let a function return a value, use the return statement:

Example

PHP Return Type Declarations

PHP 7 also supports Type Declarations for the return statement. Like with the type declaration for function arguments, by enabling the strict requirement, it will throw a «Fatal Error» on a type mismatch.

To declare a type for the function return, add a colon ( : ) and the type right before the opening curly ( < )bracket when declaring the function.

In the following example we specify the return type for the function:

Example

You can specify a different return type, than the argument types, but make sure the return is the correct type:

Example

Passing Arguments by Reference

In PHP, arguments are usually passed by value, which means that a copy of the value is used in the function and the variable that was passed into the function cannot be changed.

When a function argument is passed by reference, changes to the argument also change the variable that was passed in. To turn a function argument into a reference, the & operator is used:

Example

Use a pass-by-reference argument to update a variable:

Источник

Оцените статью