- PHP Functions
- PHP Built-in Functions
- PHP User Defined Functions
- Create a User Defined Function in PHP
- Syntax
- Example
- PHP Function Arguments
- Example
- Example
- PHP is a Loosely Typed Language
- Example
- Example
- PHP Default Argument Value
- Example
- PHP Functions — Returning values
- Example
- PHP Return Type Declarations
- Example
- Example
- Passing Arguments by Reference
- Example
- Return function name php
- User Contributed Notes 8 notes
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
«;
>
?php
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
?>?php
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:
Return function name php
PHP предоставляет большой список предопределённых констант для каждого выполняемого скрипта. Многие из этих констант определяются различными модулями и будут присутствовать только в том случае, если эти модули доступны в результате динамической загрузки или в результате статической сборки.
User Contributed Notes 8 notes
the difference between
__FUNCTION__ and __METHOD__ as in PHP 5.0.4 is that
__FUNCTION__ returns only the name of the function
while as __METHOD__ returns the name of the class alongwith the name of the function
class trick
function doit()
echo __FUNCTION__;
>
function doitagain()
echo __METHOD__;
>
>
$obj=new trick();
$obj->doit();
output will be —- doit
$obj->doitagain();
output will be —— trick::doitagain
The __CLASS__ magic constant nicely complements the get_class() function.
Sometimes you need to know both:
— name of the inherited class
— name of the class actually executed
Here’s an example that shows the possible solution:
class base_class
function say_a ()
echo «‘a’ — said the » . __CLASS__ . «
» ;
>
function say_b ()
echo «‘b’ — said the » . get_class ( $this ) . «
» ;
>
class derived_class extends base_class
function say_a ()
parent :: say_a ();
echo «‘a’ — said the » . __CLASS__ . «
» ;
>
function say_b ()
parent :: say_b ();
echo «‘b’ — said the » . get_class ( $this ) . «
» ;
>
>
$obj_b -> say_a ();
echo «
» ;
$obj_b -> say_b ();
?>
The output should look roughly like this:
‘a’ — said the base_class
‘a’ — said the derived_class
‘b’ — said the derived_class
‘b’ — said the derived_class
If you’re using PHP with fpm (common in this day and age), be aware that __DIR__ and __FILE__ will return values based on the fpm root which MAY differ from its actual location on the file system.
This can cause temporary head-scratching if deploying an app where php files within the web root pull in PHP files from outside of itself (a very common case). You may be wondering why __DIR__ returns «/» when the file itself lives in /var/www/html or whathaveyou.
You might handle such a situation by having NGINX explicitly add the necessary part of the path in its fastcgi request and then you can set the root on the FPM process / server / container to be something other than the webroot (so long as no other way it could become publicly accessible).
Hope that saves someone five minutes who’s moving code to FPM that uses __DIR__.
You cannot check if a magic constant is defined. This means there is no point in checking if __DIR__ is defined then defining it. `defined(‘__DIR__’)` always returns false. Defining __DIR__ will silently fail in PHP 5.3+. This could cause compatibility issues if your script includes other scripts.
echo ( defined ( ‘__DIR__’ ) ? ‘__DIR__ is defined’ : ‘__DIR__ is NOT defined’ . PHP_EOL );
echo ( defined ( ‘__FILE__’ ) ? ‘__FILE__ is defined’ : ‘__FILE__ is NOT defined’ . PHP_EOL );
echo ( defined ( ‘PHP_VERSION’ ) ? ‘PHP_VERSION is defined’ : ‘PHP_VERSION is NOT defined’ ) . PHP_EOL ;
echo ‘PHP Version: ‘ . PHP_VERSION . PHP_EOL ;
?>
Output:
__DIR__ is NOT defined
__FILE__ is NOT defined
PHP_VERSION is defined
PHP Version: 5.3.6
Just learned an interesting tidbit regarding __FILE__ and the newer __DIR__ with respect to code run from a network share: the constants will return the *share* path when executed from the context of the share.
// normal context
// called as «php -f c:\test.php»
__DIR__ === ‘c:\’;
__FILE__ === ‘c:\test.php’;
// network share context
// called as «php -f \\computerName\c$\test.php»
__DIR__ === ‘\\computerName\c$’;
__FILE__ === ‘\\computerName\c$\test.php’;
NOTE: realpath(‘.’) always seems to return an actual filesystem path regardless of the execution context.
Note a small inconsistency when using __CLASS__ and __METHOD__ in traits (stand php 7.0.4): While __CLASS__ is working as advertized and returns dynamically the name of the class the trait is being used in, __METHOD__ will actually prepend the trait name instead of the class name!
A lot of notes here concern defining the __DIR__ magic constant for PHP versions not supporting the feature. Of course you can define this magic constant for PHP versions not yet having this constant, but it will defeat its purpose as soon as you are using the constant in an included file, which may be in a different directory then the file defining the __DIR__ constant. As such, the constant has lost its *magic*, and would be rather useless unless you assure yourself to have all of your includes in the same directory.
Concluding: eye catchup at gmail dot com’s note regarding whether you can or cannot define magic constants is valid, but stating that defining __DIR__ is not useless, is not!
There is no way to implement a backwards compatible __DIR__ in versions prior to 5.3.0.
The only thing that you can do is to perform a recursive search and replace to dirname(__FILE__):
find . -type f -print0 | xargs -0 sed -i ‘s/__DIR__/dirname(__FILE__)/’