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