2010-03-27 11 views
52

Ho una matrice esterna:Dando il mio accesso funzione variabile fuori

$myArr = array(); 

Vorrei dare il mio accesso alle funzioni alla matrice di fuori di esso in modo che possa aggiungere valori ad esso

function someFuntion(){ 
    $myVal = //some processing here to determine value of $myVal 
    $myArr[] = $myVal; 
} 

Come posso dare alla funzione il giusto ambito per la variabile?

risposta

93

Per impostazione predefinita, quando ci si trova all'interno di una funzione, non si ha accesso alle variabili esterne.


Se si desidera la vostra funzione di avere accesso a una variabile esterna, si deve dichiarare come global, all'interno della funzione:

function someFuntion(){ 
    global $myArr; 
    $myVal = //some processing here to determine value of $myVal 
    $myArr[] = $myVal; 
} 

Per maggiori informazioni, si veda Variable scope.

Ma notare che utilizzando le variabili globali non è una buona pratica: con questo, la funzione non è più indipendente.


Un'idea migliore sarebbe quello di rendere la vostra funzione restituire il risultato:

function someFuntion(){ 
    $myArr = array();  // At first, you have an empty array 
    $myVal = //some processing here to determine value of $myVal 
    $myArr[] = $myVal;  // Put that $myVal into the array 
    return $myArr; 
} 

e chiamare la funzione come questa:

$result = someFunction(); 


La funzione potrebbe anche prendere i parametri e anche funziona su un parametro passato per riferimento:

function someFuntion(array & $myArr){ 
    $myVal = //some processing here to determine value of $myVal 
    $myArr[] = $myVal;  // Put that $myVal into the array 
} 

Poi, chiamare la funzione in questo modo:

$myArr = array(...); 
someFunction($myArr); // The function will receive $myArr, and modify it 

Con questo:

  • La funzione ha ricevuto la matrice esterna come parametro
  • E può modificarlo, come è passato per riferimento.
  • Ed è prassi migliore rispetto all'utilizzo di una variabile globale: la tua funzione è un'unità indipendente da qualsiasi codice esterno.


Per maggiori informazioni su questo, si dovrebbe leggere la sezione Functions del manuale di PHP, e ,, in particolare, le seguenti sottosezioni:

+1

Che dire di tutti i voti negativi? – PatrikAkerstrand

+2

@Machine: una bella domanda ^^ * (Ho, da allora, modificato la mia risposta un paio di volte per aggiungere ulteriori informazioni, forse è stato downvoted perché non abbastanza completo, all'inizio ... Probabilmente ha qualcosa a che fare con globale, a cui la gente non piace ...) * –

+3

@Machine Mr Anti-Global @Coronatus ha deciso che le risposte perfettamente valide sono sbagliate. E il suo rappresentante di 1,662 gli fa bene ... –

8
$myArr = array(); 

function someFuntion(array $myArr) { 
    $myVal = //some processing here to determine value of $myVal 
    $myArr[] = $myVal; 

    return $myArr; 
} 

$myArr = someFunction($myArr); 
+6

Stupido downvoting. Naturalmente, questa è l'unica risposta corretta nell'intero thread. – user187291

2

L'unico e probabilmente non così buono modo di raggiungere il tuo obiettivo sarebbe utilizzare le variabili globali.

È possibile ottenere ciò aggiungendo global $myArr; all'inizio della funzione. Tuttavia, notare che l'utilizzo di variabili globali è nella maggior parte dei casi un'idea sbagliata e probabilmente evitabile.

Il modo migliore sarebbe passato l'array come argomento alla funzione:

function someFuntion($arr){ 
    $myVal = //some processing here to determine value of $myVal 
    $arr[] = $myVal; 
    return $arr; 
} 

$myArr = someFunction($myArr); 
7
Global $myArr; 
$myArr = array(); 

function someFuntion(){ 
    global $myArr; 

    $myVal = //some processing here to determine value of $myVal 
    $myArr[] = $myVal; 
} 

essere avvertiti, in genere la gente bastone da variabili globali in quanto ha alcuni aspetti negativi.

Si potrebbe provare questo

function someFuntion($myArr){ 
    $myVal = //some processing here to determine value of $myVal 
    $myArr[] = $myVal; 
    return $myArr; 
} 
$myArr = someFunction($myArr); 

che renderebbe quindi non si affidano a Globali.

+0

Il globale all'interno dell'ambito della funzione sarebbe sufficiente, ne hai aggiunto uno allo scopo "principale" intenzionalmente? Buona pratica? (mai usando i globali ..) – svens

+0

Il "globale" al di fuori della funzione è inutile, a meno che l'intero file non sia stato incluso da un'altra funzione. – andreszs

7
$foo = 42; 
$bar = function($x = 0) use ($foo){ 
    return $x + $foo; 
}; 
var_dump($bar(10)); // int(52) 
+0

Così elegante ... Bella risposta! –

0

Due risposte

1. Risposta alla domanda posta.

2. Un semplice cambiamento equivale a un modo migliore!

Risposta 1 - Passare il Vars Array al __construct() in una classe, è possibile lasciare il costrutto vuoto e passare gli array tramite le funzioni.

<?php 

// Create an Array with all needed Sub Arrays Example: 
// Example Sub Array 1 
$content_arrays["modals"]= array(); 
// Example Sub Array 2 
$content_arrays["js_custom"] = array(); 

// Create a Class 
class Array_Pushing_Example_1 { 

    // Public to access outside of class 
    public $content_arrays; 

    // Needed in the class only 
    private $push_value_1; 
    private $push_value_2; 
    private $push_value_3; 
    private $push_value_4; 
    private $values; 
    private $external_values; 

    // Primary Contents Array as Parameter in __construct 
    public function __construct($content_arrays){ 

     // Declare it 
     $this->content_arrays = $content_arrays; 

    } 

    // Push Values from in the Array using Public Function 
    public function array_push_1(){ 

     // Values 
     $this->push_values_1 = array(1,"2B or not 2B",3,"42",5); 
     $this->push_values_2 = array("a","b","c"); 

     // Loop Values and Push Values to Sub Array 
     foreach($this->push_values_1 as $this->values){ 

      $this->content_arrays["js_custom"][] = $this->values; 

     } 

     // Loop Values and Push Values to Sub Array 
     foreach($this->push_values_2 as $this->values){ 

      $this->content_arrays["modals"][] = $this->values; 

     } 

    // Return Primary Array with New Values 
    return $this->content_arrays; 

    } 

    // GET Push Values External to the Class with Public Function 
    public function array_push_2($external_values){ 

     $this->push_values_3 = $external_values["values_1"]; 
     $this->push_values_4 = $external_values["values_2"]; 

     // Loop Values and Push Values to Sub Array 
     foreach($this->push_values_3 as $this->values){ 

      $this->content_arrays["js_custom"][] = $this->values; 

     } 

     // Loop Values and Push Values to Sub Array 
     foreach($this->push_values_4 as $this->values){ 

      $this->content_arrays["modals"][] = $this->values; 

     } 

    // Return Primary Array with New Values 
    return $this->content_arrays; 

    } 

} 

// Start the Class with the Contents Array as a Parameter 
$content_arrays = new Array_Pushing_Example_1($content_arrays); 

// Push Internal Values to the Arrays 
$content_arrays->content_arrays = $content_arrays->array_push_1(); 

// Push External Values to the Arrays 
$external_values = array(); 
$external_values["values_1"] = array("car","house","bike","glass"); 
$external_values["values_2"] = array("FOO","foo"); 
$content_arrays->content_arrays = $content_arrays->array_push_2($external_values); 

// The Output 
echo "Array Custom Content Results 1"; 
echo "<br>"; 
echo "<br>"; 

echo "Modals - Count: ".count($content_arrays->content_arrays["modals"]); 
echo "<br>"; 
echo "-------------------"; 
echo "<br>"; 

// Get Modals Array Results 
foreach($content_arrays->content_arrays["modals"] as $modals){ 

    echo $modals; 
    echo "<br>"; 

} 

echo "<br>"; 
echo "JS Custom - Count: ".count($content_arrays->content_arrays["js_custom"]); 
echo "<br>"; 
echo "-------------------"; 
echo "<br>"; 

// Get JS Custom Array Results 
foreach($content_arrays->content_arrays["js_custom"] as $js_custom){ 

    echo $js_custom; 
    echo "<br>"; 


} 

echo "<br>"; 

?> 

Risposta 2 - Un semplice cambiamento tuttavia avrebbe messo in linea con gli standard moderni. Basta dichiarare i tuoi array nella classe.

<?php 

// Create a Class 
class Array_Pushing_Example_2 { 

    // Public to access outside of class 
    public $content_arrays; 

    // Needed in the class only 
    private $push_value_1; 
    private $push_value_2; 
    private $push_value_3; 
    private $push_value_4; 
    private $values; 
    private $external_values; 

    // Declare Contents Array and Sub Arrays in __construct 
    public function __construct(){ 

     // Declare them 
     $this->content_arrays["modals"] = array(); 
     $this->content_arrays["js_custom"] = array(); 

    } 

    // Push Values from in the Array using Public Function 
    public function array_push_1(){ 

     // Values 
     $this->push_values_1 = array(1,"2B or not 2B",3,"42",5); 
     $this->push_values_2 = array("a","b","c"); 

     // Loop Values and Push Values to Sub Array 
     foreach($this->push_values_1 as $this->values){ 

      $this->content_arrays["js_custom"][] = $this->values; 

     } 

     // Loop Values and Push Values to Sub Array 
     foreach($this->push_values_2 as $this->values){ 

      $this->content_arrays["modals"][] = $this->values; 

     } 

    // Return Primary Array with New Values 
    return $this->content_arrays; 

    } 

    // GET Push Values External to the Class with Public Function 
    public function array_push_2($external_values){ 

     $this->push_values_3 = $external_values["values_1"]; 
     $this->push_values_4 = $external_values["values_2"]; 

     // Loop Values and Push Values to Sub Array 
     foreach($this->push_values_3 as $this->values){ 

      $this->content_arrays["js_custom"][] = $this->values; 

     } 

     // Loop Values and Push Values to Sub Array 
     foreach($this->push_values_4 as $this->values){ 

      $this->content_arrays["modals"][] = $this->values; 

     } 

    // Return Primary Array with New Values 
    return $this->content_arrays; 

    } 

} 

// Start the Class without the Contents Array as a Parameter 
$content_arrays = new Array_Pushing_Example_2(); 

// Push Internal Values to the Arrays 
$content_arrays->content_arrays = $content_arrays->array_push_1(); 

// Push External Values to the Arrays 
$external_values = array(); 
$external_values["values_1"] = array("car","house","bike","glass"); 
$external_values["values_2"] = array("FOO","foo"); 
$content_arrays->content_arrays = $content_arrays->array_push_2($external_values); 

// The Output 
echo "Array Custom Content Results 1"; 
echo "<br>"; 
echo "<br>"; 

echo "Modals - Count: ".count($content_arrays->content_arrays["modals"]); 
echo "<br>"; 
echo "-------------------"; 
echo "<br>"; 

// Get Modals Array Results 
foreach($content_arrays->content_arrays["modals"] as $modals){ 

    echo $modals; 
    echo "<br>"; 

} 

echo "<br>"; 
echo "JS Custom - Count: ".count($content_arrays->content_arrays["js_custom"]); 
echo "<br>"; 
echo "-------------------"; 
echo "<br>"; 

// Get JS Custom Array Results 
foreach($content_arrays->content_arrays["js_custom"] as $js_custom){ 

    echo $js_custom; 
    echo "<br>"; 


} 

echo "<br>"; 

?> 

Sia uscita mangiare le stesse informazioni e consentire una funzione di spingere e recuperare informazioni da un array e sub array a qualsiasi punto del codice (Dato che i dati è stato spinto prima). La seconda opzione offre un maggiore controllo sul modo in cui i dati vengono utilizzati e protetti. Possono essere utilizzati come è solo modificare le vostre esigenze, ma se sono stati utilizzati per estendere un controller potrebbero condividere i loro valori tra una qualsiasi delle classi che il controller sta utilizzando.Nessuno dei due metodi richiede l'uso di un Global (s).

uscita:

Array Custom Content Risultati

Modals - Numero di pagine: 5

un

b

c

FOO

foo

JS personalizzata - Count: 9

2B o meno 2B

auto

casa

moto

vetro

Problemi correlati