Bir fonksiyon içerisinde olduğunda, varsayılan olarak, siz dış değişkenlere erişimi yok.
If you want your function to have access to an outer variable, you have to declare it as global, inside the function :
function someFuntion(){
global $myArr;
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
}
Daha fazla bilgi almak için, Variable scope a> bakın.
Bu, sizin işlevi artık independant değildir: Ama using global variables is not a good practice unutmayın.
A better idea would be to make your function return the result :
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;
}
Ve bu gibi işlevi çağırır:
$result = someFunction();
Your function could also take parameters, and even work on a parameter passed by reference :
function someFuntion(array & $myArr){
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal; // Put that $myVal into the array
}
Sonra, bu gibi işlevi çağırır:
$myArr = array( ... );
someFunction($myArr); // The function will receive $myArr, and modify it
Bu grubu:
- Sizin fonksiyonu parametre olarak harici diziyi aldı
- Bu referans ile iletilen Ve, bunu değiştirebilirsiniz.
- Ve küresel bir değişken kullanarak daha iyi bir uygulamadır: işlev herhangi bir dış kod birimi, bağımsızdır.
For more informations about that, you should read the Functions section of the PHP manual, and,, especially, the following sub-sections :