Chose Language:
Author: Admin/Publisher |finished | checked

PHP functions

Functions in PHP are blocks of code or subalgorithms that can be reused and help solve a specific task. Functions must be defined before they are called or referenced.

Topics:

Defined functions

https://blastcoding.com/en/php-functions/#defined_functions

The defined function is the function to which we give a name. The name of a function must start with a letter or underscore. To declare a function, you must use the keyword function.

ejemplo de función definida
<?php
function saludo(){ //declaracion de la funcion saludo
   echo "holaa !!";
}

saludo();// llamo a la funcion saludo


?>

As we can see, we define a function using the function keyword and call it with the name we have given, in this case, saludo().

We can also pass parameters to a function, as shown in the following example.

paso de parámetro a función
<?php
function saludo($nombre){
   echo "hola $nombre !!";
}

saludo("Luis");
saludo("Mariam");


?>

Passing parameters by reference to a function. Next, let’s see the difference between the two approaches.

Ejemplo- paso de parámetro por referencia
<?php
    $a = 0;
    $b = 0;
    echo "tanto la variable a como b partiran con el mismo valor y veremos como cambia pasar algo por referencia o no";

    function porReferencia(&$n){
        $n = 2;
    }
    function sinReferencia($n){
        $n = 2;
    }

    porReferencia($a);
    echo "<br/>el valor de a: ".$a;
    sinReferencia($b);
    echo "<br/>el valor de b: ".$b;
    //como puede ver el valor de a ahora será 2 y el de b seguirá siendo 0
    //esta es la diferencia de usar una variable por referencia
?>

Variable functions in PHP

https://blastcoding.com/en/php-functions/#variable_functions

If a variable is followed by two parentheses () in example $name(), it will take the value of the variable as its name, and these are called variable functions. Obviously, the variable must have a string value that follows the rules for function names.

Ejemplo simple de funciones variables
<?php
function hola(){
    echo "hola a todos";
}
$name= "hola"
$name();
?>

Funciones (build-in)

https://blastcoding.com/en/php-functions/#built-in-functions

Another type of functions in PHP comes with many pre-installed functions, and others will fail if we try to use them without the required extensions installed, for example, mysqli, curl, and others. Many of these extensions come pre-installed if we use a LAMP, WAMP, or similar stack.

Anonymous functions in PHP

https://blastcoding.com/en/php-functions/#anonymous_functions

In anonymous functions, they do not have a specific name and can be used as a callback, saved in a variable, or directly used as a function. I believe I have used one in a variable once. Anyway, here are some examples.

Ejemplo de Función anónima
<?php
    
    $name = function($var){
        if(is_numeric($var)):
            return "es un numero";
        elseif(is_array($var)):
            return "es un array";
        else:
            return "no es un numero ni un array";
        endif;
    };

    echo $name(array(1,2));
?>

The following is a direct example from php.net

<?php
echo preg_replace_callback('~-([a-z])~', function ($coincidencia) {
    return strtoupper($coincidencia[1]);
}, 'hola-mundo');
// imprime holaMundo
?>
In the previous example we are using an anonimus function as a callback

Utilizando use

https://blastcoding.com/en/php-functions/#anonymous_functions_use

Since PHP 7.1, you can use the term use to refer to variables in the parent scope of an anonymous function.

Using the keyword use
<?php
$mensaje = 'hola';// Sin "use"
$ejemplo = function () {
    var_dump($mensaje);
};
$ejemplo();//$mensaje?
$ejemplo = function () use ($mensaje) {
    var_dump($mensaje);
};
$ejemplo();
July 20, 2023 – Something I had forgotten to mention about anonymous functions is that they can be executed without being assigned to a variable. These are called immediately-invoked anonymous functions (IIFE).

This type of function, combined with heredoc, can be very useful for WordPress or any PHP project.

Also, you won’t have unnecessary global variables, making it a very good option. Let’s quickly see its syntax:

(function(){
// tu codigo va aqui
})();

Let’s see a really simple example:

(function() {
    echo "This is an IIFE in PHP!";
})();

Return types in functions

https://blastcoding.com/en/php-functions/#return_types_in_functions

You can also predefine the return value type of a function by using : followed by the type it will return, or “void” if the function won’t return anything.

sintaxis:
function nombre_funcion () : tipo_de_variable
definiendo que tipo de dato retorna
function llamar ($nombre) : string {
        return "llamando a $nombre";
}

It is likely that we will have to use declare(strict_types=1) in modern PHP development. The idea is to declare this line almost at the beginning of our project so that strict typing is enforced throughout the program.

Nullable return types

https://blastcoding.com/en/php-functions/#nullable_return_types

To allow a return value to be null, we need to add a question mark (?) before the return type ?

function llamar ($nombre) : ?string {
        return "llamando a $nombre";
}

Data type declaration in function parameters (since PHP 7.4)

https://blastcoding.com/en/php-functions/#parameter_data_type

PHP 7.4 brought along some new features, such as the ability to declare the data type of a variable in the argument. This is extremely useful as it allows us to know with certainty the type(s) of data we are passing to that function.

definiendo que tipo de datos pasamos por parámetro
<?php

function holamundo(string $a, string $b){
    echo $a." ".$b;
}
holamundo("hola","mundo");

By default, PHP will try to change the type of the variable to the expected type. To prevent this, you can use the statement declare(strict_types=1);. This way, we are forcing the passed variable to be of the expected type. In case it is not, it will give us an error.

Let’s see some examples using the previous function.

Without using Strict type:

Sin declare(strict_type=1)
<?php

function holamundo(string $a, string $b){
    echo $a." ".$b;
}
holamundo(1,"mundo");
1 mundo

Now we will see the difference of Strict type

Con declare(strict_type=1)
<?php

declare(strict_types=1);

function holamundo(string $a, string $b){
    echo $a." ".$b;
}
holamundo(1,"mundo");
Fatal error: Uncaught TypeError: holamundo(): Argument #1 ($a) must be of type string, int given, called in C:\xampp\htdocs\tutorialphp\funciones.php on line 6 and defined in C:\xampp\htdocs\tutorialphp\funciones.php:3 Stack trace: #0 C:\xampp\htdocs\tutorialphp\funciones.php(6): holamundo(1, 'mundo') #1 {main} thrown in C:\xampp\htdocs\tutorialphp\funciones.php on line 3

Nullable parameters

https://blastcoding.com/en/php-functions/#nullable_parameters

To allow an argument to be null, in addition to specifying its data type, we need to add the ? symbol before the data type we specified.

Let’s take the previous code as an example:

<?php

declare(strict_types=1);

function holamundo(?string $a, string $b){
    echo $a." ".$b;
}
holamundo(NULL,"mundo");

Now, $a can be null, and the issue is that now I have to handle null values. For example, if $a is null, I want to assign a default value to it. If I run it as it is, it will only output “mundo.”

Referencia:php.net

Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category