Benim PHP İşlev çalışmıyor

6 Cevap php

Ben aşağıdaki kod ile sorun yaşıyorum. Ne yapmalıyım example.php takip yankı cats.php ama example.php yankılanan değil. Neden herhangi bir fikir oluyor olabilir?

$bookLocations = array(
    'example.php',
    'cats.php',
    'dogs.php',
    'fires.php',
    'monkeys.php',
    'birds.php',
);

echo $bookLocations[1];

function findfile($filenumber)
{
echo $bookLocations["$filenumber"];
}

findfile(0);

6 Cevap

i de işlevi küresel değişkeni bildirmek gerekebilir inanıyorum.

global $bookLocations;

Değiştirmeyi deneyin,

echo $bookLocations["$filenumber"];

için:

echo $bookLocations[$filenumber];

Edit* To expand on Thomas's correct answer, instead of using global variables, you could change your method için:

function findfile($filenumber, $bookLocations)
{
    echo $bookLocations[$filenumber];
}

Tamam, iki konu vardır.

Variable Scope

Sizin işlevi dizi bilmiyor $bookLocations, bunu gibi işleve geçmesi gerekir:

function findfile($filenumber, $bookLocations)

Array key

Tırnak içinde dizi anahtarı sarmak istemiyorum:

wrong: $bookLocations["$filenumber"];
right: $bookLocations[$filenumber];

Lütfen dizi anahtarları tüm sayılar ne zaman tırnak "$filenumber", bir dizeye anahtar açın. Demek ki, 1 ([{- Sen aslında sen want erişimi $bookLocations[1] zaman $bookLocations["1"] erişmeye çalıştığınız 5)]} ile aynı "1". Diğerleri gibi söylediler, bu nedenle, anahtarın etrafında tırnak kurtulmak (ve çok değişken kapsamını kontrol) gerekir.

function findfile($filenumber)
{
  global $bookLocations;
  echo $bookLocations[$filenumber];
}

İyi-style geliştiriciler genellikle küresel değişkenler önlemek. Bunun yerine, parametre olarak işleve dizi geçirmek:

function findfile($files, $filenum)
{
  echo $files[$filenum];
}

$ BookLocations sizin fonksiyonu için kapsam dışında. Eğer $ filenumber echo Eğer bu değeri geçti çünkü kapsam içinde olduğunu göreceksiniz. Ancak, $ bookoLocations için hiçbir başvuru yoktur.

Sen $ bookLocations geçmek gerekir

declaration: function findfile($filenumber, $bookLocations){ call: findfile(1, $bookLocations);

Ayrıca, küresel olarak $ bookLocations ilan verebilir, ama mümkünse globallerinin kaçınılmalıdır.