Undefined variable in PHP

1

What kind of colleagues I need your help, I have been alleviating an error that has overwhelmed me for many hours and I can not solve it before it worked but my PC formats and it does not work anymore, it sends me an error when I try to create a list for each worker and send error when inserting data, the error is for the image but I tried everything and it is not solved, the records are not inserted in MySQL. I will thank you all my life, Thank you! :)

This is the insert code where the error is sent ...

here is the error  and this is the error that comes out in PHP

and it should come out like this ...

    
asked by MetalxD117 20.06.2018 в 06:19
source

1 answer

1

You are facing a scope problem of PHP functions / variables.

The variable you want to use is here:

function subirImagen() {

    $nombre_img="...";

    //código

}

You can not use it out of there , unless you return it from within the function.

In that case, you would have to put a return at the end:

function subirImagen() {

    $nombre_img="...";

    //código

    /*Esta debe ser la última línea*/
    return $nombre_img;

}

And, in the part of the code where you want to use the variable, outside its scope , you type this:

$nombre_img=subirImagen(); //Aquí tomará el valor del return

$db->insertar(....);

This would be practical only if the only thing you want to use outside of subirImagen() is the name of that variable. If you need other variables you should return an array with each of them, or, better, design the code based on a Clase to be able to use its properties and methods more easily and have the code more organized.

Some tests

Let's see some evidence of the above. You can check the complete code in this DEMO .

Test 1: how do you have the code now?

It does not work because you try to use the variable outside its scope

/*
    *Prueba 1:
        - No funcionará porque se usa la variable fuera de su ámbito
*/
function subirImagenSinReturn() {

    $nombre_img="imagen.jpg";
    $size_img="100kb";
}

subirImagenSinReturn();
echo $nombre_img;

Exit:

  

PHP Notice: Undefined variable: name_img in source_file.php on line   14

Test 2: returning the variable from its scope

/*
    *Prueba 2:
        - Se trae la variable llamando a la función, mediante el return
        - Recomendable en algunos casos, y si sólo interesa un dato de la función
*/
function subirImagenConReturn() {
    $nombre_img="imagen.jpg";
    $size_img="100kb";
    return $nombre_img;
}

$nombre_img=subirImagenConReturn();
echo $nombre_img.PHP_EOL;

Exit:

imagen.jpg

Test 3: obtaining several data using an array

/*
    *Prueba 3:
        - Se traen varias variables en un array mediante el return
        - Poco recomendable, porque luego habría que buscar cada variable
          dentro de array.
        - En vez de esto convendría quizá pensar en una clase (ver Prueba 4)
*/
function subirImagenConReturnMultiple() {
    $nombre_img="imagen.jpg";
    $size_img="100kb";
    return array("nombre"=>$nombre_img, "size"=>$size_img);
}

$arrDatos=subirImagenConReturnMultiple();
$nombre_img=$arrDatos["nombre"];
$size_img=$arrDatos["size"];
echo $nombre_img.PHP_EOL;
echo $size_img.PHP_EOL;

Exit:

imagen.jpg
100kb

Test 4: Using a class

Here we enter another field, but very interesting: Object Oriented Programming (OOP). It is a modern paradigm of programming that will be very useful in the future.

/*
    *Prueba 4:
        - Mediante una Clase
        - Se declaran las variables como miembros de la clase.
        - Se puede acceder a ellas desde cualquier parte de la clase
        - Antes de optar por esta solución convendría informarse sobre qué son la Clases
          qué es la Programación Orientada a Objetos, etc. 
          Para no crear clases de forma indiscriminada
          La programación con clases es una potente herramienta para resolver
          problemas complejos, mantener el código organizado, evitar la repetición de código, etc.
          Algo esencial, sobre toco cuando se empieza, es pensar la clase como una entidad única
          no como entidades separadas. Así, podemos hablar de la clase Persona, la clase Imagen, etc
          las cuales tendrían todos los atributos de esa entidad como nombre, tamaño, color...

*/


class Imagen {
    private $nombre_img;
    private $size_img;

    public function __construct(){

    }

    public function subirImagen(){
        //Código relativo a la subida de imágenes
        $this->nombre_img="imagen.jpg";
        $this->size_img="100kb";              
    }

    public function insertarImagen(){

        $this->subirImagen();
        echo $this->nombre_img.PHP_EOL;
        echo $this->size_img.PHP_EOL;

    }

}
/*
    -Modo de uso de la clase:
       Creas una instancia de la clase 
       y tienes acceso a sus miembros usando la instancia
*/
$myImagen=new Imagen();
$myImagen->insertarImagen();

Exit:

imagen.jpg
100kb
    
answered by 20.06.2018 / 07:13
source