我在代码开头声明了一个数组
$animal = array (
"Dog",
"Cat");
现在我希望能够在方法中使用这些值。我想远离可用的全局解决方案,并且想知道是否有办法通过再次创建数组来做到这一点?
例如创建一个新数组
$animal_store = array();
然后循环浏览原始数组并将值附加到新数组。这可能吗?
这些例子有帮助吗?
$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
现在;你想将一个数组传递到你的函数中,而不是打印每个项目,你想 HINT 将 HINT 项目推送到另一个数组中。
我建议你的函数返回一个数组,并为返回的函数分配一个变量。
class Test {
public static $animal = array("cat", "dog");
}
现在,您可以在所有方法中使用此静态成员
是的,这是可能的
$animal = array (
"Dog",
"Cat"
);
function addNew(){
global $animal;
// just by adding this you can access the array
}
因此,如果您不想使用全局,请尝试将数组写入另一个文件,例如 config.php
.然后将其包含在函数中并返回数组
配置.php
$animal = array (
"Dog",
"Cat"
);
您的当前页面
function getArray(){
require('config.php');
if(is_array($animal))
return $animal;
else
return false;
}
然后在函数 u 想要中调用它
function doJob(){
echo "<pre>";
$animal = getArray();
var_dump($animal);
}