如何从 PHP 文件加载返回数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7073672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:57:31  来源:igfitidea点击:

How to load return array from a PHP file?

phparraysinclude

提问by bman

I have a PHP file a configuration file coming from a Yiimessage translation file which contains this:

我有一个 PHP 文件,一个来自Yii消息翻译文件的配置文件,其中包含以下内容:

<?php
 return array(
  'key' => 'value'
  'key2' => 'value'
 );
?>

I want to load this array from another file and store it in a variable

我想从另一个文件加载这个数组并将其存储在一个变量中

I tried to do this but it doesn't work

我试图这样做,但它不起作用

function fetchArray($in)
{
   include("$in");
}

$inis the filename of the PHP file

$in是 PHP 文件的文件名

Any thoughts how to do this?

任何想法如何做到这一点?

回答by Phil

When an included file returns something, you may simply assign it to a variable

当包含的文件返回某些内容时,您可以简单地将其分配给一个变量

$myArray = include $in;

See http://php.net/manual/function.include.php#example-126

http://php.net/manual/function.include.php#example-126

回答by Jason

Returning values from an include file

从包含文件返回值

We use this in our CMS. You are close, you just need to return the value from that function.

我们在我们的 CMS 中使用它。你很接近,你只需要从该函数返回值。

function fetchArray($in)
{
  if(is_file($in)) 
       return include $in;
  return false
}

See example 5# here

在此处查看示例 5#

回答by Nishad Up

As the file returning an array, you can simply assign it into a variable

当文件返回一个数组时,您可以简单地将其分配给一个变量

Here is the example

这是例子

$MyArray = include($in);
print_r($MyArray);

Output:

输出:

Array
(
    [key] => value
    [key2] => value
)