在函数PHP中使用全局数组

时间:2015-03-12 12:46:12

标签: php arrays

我在代码的开头声明了一个数组

    $animal = array (
    "Dog",
    "Cat");

现在我希望能够在方法中使用这些值。我想远离可用的全球解决方案,并想知道是否有办法通过再次创建阵列来实现这一目标?

例如创建一个新数组

$animal_store = array();

然后遍历原始数组并将值附加到新数组。这可能吗?

3 个答案:

答案 0 :(得分:1)

这些例子中的任何一个都有帮助吗?

$animals = ['Dog', 'Cat', 'Cobra Kai'];

class Zoo {
  protected $animals;

  public function setAnimals($animals)
  {
    $this->animals = $animals;
  }

  public function getAnimals()
  {
    return $this->animals;
  }
}

class NoInvestorsZoo extends Zoo {

  public function __construct()
  {
     // We have nothing to start out with, hopefully we can setAnimals some time...
  }

}

class LotsOfInvestorsZoo extends Zoo {

  public function __construct($animals)
  {
     $this->setAnimals($animals);
     // No serious investor would start a zoo without having animals!
  }

}

// For our zoo to be populated we could...

$iLoveAnimals = new NoInvestorsZoo;
// After lots of lunch meetings and fund raisers...
$iLoveAnimals->setAnimals($animals); // Hooray!!

// Meanwhile

$capitalistPigsRUs = new LotsOfInvestorsZoo($animals);
// Mohahaha!

无论哪种方式,我们都可以

$iLoveAnimals->getAnimals();

或者

$capitalistPigsRUs->getAnimals();


请看下面的例子。

$array = ['Dog', 'Cat', 'Giraffe']; // Our animals array

function animalsInOurZoo($animals) // Our function takes one argument
{
  foreach ($animals as $animal) // Loop through our array
    echo $animal . '\n'; // Print out each item.
}

animalsInOurZoo($array); // We pass our animals into our function

现在;如果要将数组传递到函数中并打印每个项目,则需要提示提示项目推送到另一个数组中。

我建议您的函数返回一个数组,并为返回的函数指定一个变量。

答案 1 :(得分:0)

class Test {
    public static $animal = array("cat", "dog");
}

现在你可以在所有方法中使用这个静态成员

答案 2 :(得分:-1)

是的,有可能

$animal = array (
    "Dog",
    "Cat"
);
function addNew(){
    global $animal;
    // just by adding this you can access the array
}

因此,如果您不想使用global,请尝试将该数组写入另一个文件config.php。然后将其包含在函数中并返回数组

的config.php

$animal = array (
    "Dog",
    "Cat"
);

您当前的页面

function getArray(){
    require('config.php');
    if(is_array($animal))
        return $animal;
    else
        return false;
}

然后在函数u desired

中调用它
function doJob(){
    echo "<pre>";
    $animal = getArray();
    var_dump($animal);
}