2009-11-24 11 views
6

Tengo esta función que declara variables:hacer que las variables estén disponibles fuera de la función en PHP?

function imageSize($name, $nr, $category){ 
    $path = 'ad_images/'.$category.'/'.$name.'.jpg'; 
    $path_thumb = 'ad_images/'.$category.'/thumbs/'.$name.'.jpg'; 
    list($width, $height) = getimagesize($path); 
    list($thumb_width, $thumb_height) = getimagesize($path_thumb); 
     ${'thumb_image_' . $nr . '_width'} = $thumb_width; 
     ${'thumb_image_' . $nr . '_height'} = $thumb_height; 
     ${'image_' . $nr . '_width'} = $width; 
     ${'image_' . $nr . '_height'} = $height; 
} 

Cuando me hago eco de esto:

echo $image_1_width 

Funciona bien, pero si lo hago fuera de la función no lo puedo reconocer la variable, ¿cómo puedo hacerlos 'globales' de alguna manera?

Gracias

Respuesta

13

Yo recomendaría encarecidamente NOT usando global.

lo que probablemente será mejor es para que usted regrese de la función:

function imageSize($name, $nr, $category){ 
    $path = 'ad_images/'.$category.'/'.$name.'.jpg'; 
    $path_thumb = 'ad_images/'.$category.'/thumbs/'.$name.'.jpg'; 
    list($width, $height) = getimagesize($path); 
    list($thumb_width, $thumb_height) = getimagesize($path_thumb); 
     ${'thumb_image_' . $nr . '_width'} = $thumb_width; 
     ${'thumb_image_' . $nr . '_height'} = $thumb_height; 
     ${'image_' . $nr . '_width'} = $width; 
     ${'image_' . $nr . '_height'} = $height; 

    $myarr = array(); 
    $myarr['thumb_image_' . $nr . '_width'] = $thumb_width; 
    $myarr['thumb_image_' . $nr . '_height'] = $thumb_height; 
    $myarr['image_image_' . $nr . '_width'] = $width; 
    $myarr['image_image_' . $nr . '_height'] = $height; 
    return $myarr; 

} 

$myImage = imageSize($name, $nr, $category);

entonces acceder a cada var:

echo $myImage['thumb_image_1_width']; 
echo $myImage['thumb_image_1_height']; 
echo $myImage['image_1_weight']; 
echo $myImage['image_1_height']; 

etc.

8

Tendrá que definirlas fuera de la función. Y dentro de la función de utilizar la palabra clave global antes de que se utilicen:

$someVar = null; 

function SomeFunc() { 
    global $someVar; 
    // change $someVar 
} 

// somewhere later 
SomeFunc(); 
echo $someVar; 

ser advertidos, sin embargo, que esta es una muy mala elección de diseño!

+4

De acuerdo. Recomiendo que la función devuelva esos valores como una matriz en lugar de usar globales. –

+0

¿por qué es malo? dame algunos argumentos también ... –

+3

Si usas globales, nunca sabes cuándo y quién los modificará y se rompe el flujo del código. Mire algunas de las sugerencias en otras respuestas para obtener pistas sobre cómo reescribir su función (sugerencia: devuelva lo que necesita) –

-1
$var = 4; 

function bla() 
{ 
    global $var; 
    return $var; 
} 

Volverá 4, ya que la variable es global. Espero que esto es lo que quieres.

+1

return es muy diferente de echo. – davethegr8

0

retorno el valor dentro de la función en lugar de usar globals

1

Parece que desea implementar una clase en lugar de una función. Algo como:

class myImage { 

    function __construct($name, $nr, $category){ 
     $path = 'ad_images/'.$category.'/'.$name.'.jpg'; 
     $path_thumb = 'ad_images/'.$category.'/thumbs/'.$name.'.jpg'; 
     list($width, $height) = getimagesize($path); 
     list($thumb_width, $thumb_height) = getimagesize($path_thumb); 
     $this->{'thumb_image_' . $nr . '_width'} = $thumb_width; 
     $this->{'thumb_image_' . $nr . '_height'} = $thumb_height; 
     $this->{'image_' . $nr . '_width'} = $width; 
     $this->{'image_' . $nr . '_height'} = $height; 
    } 
} 

$image= new myImage($name, $nr, $category); 
echo $image->'image_1_width'; 

Por supuesto, con este tipo de construcción, no es necesario pegar los nombres de las variables. Solo puede tener $image->width.

2

También puede crear una matriz o un objeto y luego devolver esa información; por ejemplo,

$dimensions[$nr] = imageSize($name,$category); 
echo "Thumb width " . $dimensions[$nr]['thumb_width']; 

Luego, en la propia función

function imageSize($name, $category) 
{ 
    $path = 'ad_images/'.$category.'/'.$name.'.jpg'; 
    $path_thumb = 'ad_images/'.$category.'/thumbs/'.$name.'.jpg'; 
    list($width, $height) = getimagesize($path); 
    list($thumb_width, $thumb_height) = getimagesize($path_thumb); 

    $rsvp = Array(); 
    $rsvp['thumb_width'] = $thumb_width; 
    $rsvp['thumb_height'] = $thumb_height; 
    $rsvp['image_width'] = $width; 
    $rsvp['image_height'] = $height; 

    return $rsvp; 
} 
1

Me segundos @ respuesta de lagarto. Además, parece que leer en variable scope un poco no iría mal. (Tenga en cuenta que ese enlace incluye una explicación de cómo usar las variables globales. Como muchos aquí han dicho, eso es no el mejor camino para bajar.)

2

Me sorprende que nadie haya pensado en hablar sobre el extracto . Tomará los valores de una matriz y los convertirá en variables locales.Por lo tanto, en este caso:

function imageSize($name, $nr, $category){ 
    $path = 'ad_images/'.$category.'/'.$name.'.jpg'; 
    $path_thumb = 'ad_images/'.$category.'/thumbs/'.$name.'.jpg'; 

    $myarr = array(); 
    $myarr['thumb_image_' . $nr . '_width'] = $thumb_width; 
    $myarr['thumb_image_' . $nr . '_height'] = $thumb_height; 
    $myarr['image_image_' . $nr . '_width'] = $width; 
    $myarr['image_image_' . $nr . '_height'] = $height; 
    return $myarr; 

} 

$myImage = imageSize('myName', 'foo', $category); 
extract($myImage); 

Ahora tendrá las variables,

$thumb_image_foo_width; 
$thumb_image_foo_height; 
$image_image_foo_width; 
$image_image_foo_height; 

de alcance local.

+0

¡Un gran punto! No sabía sobre 'extract()' antes. Siempre he usado: 'while (list ($ key, $ val) = each ($ array)) {$$ key = $ val;}'. + 1. – Kit

0

Si declara la variable como parte de la matriz $ GLOBALS, la agregará al alcance global.

$GLOBALS['variable name'] = 'value'; 

Como han mencionado otros, los globales deben inicializarse en el ámbito global, por ejemplo, en NULL.

Cuestiones relacionadas