简体   繁体   English

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

[英]How to load return array from a PHP file?

I have a PHP file a configuration file coming from a Yii message 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");
}

$in is the filename of the PHP file $in是 PHP 文件的文件名

Any thoughts how to do this?任何想法如何做到这一点?

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-126http://php.net/manual/function.include.php#example-126

Returning values from an include file从包含文件返回值

We use this in our CMS.我们在 CMS 中使用它。 You are close, you just need to return the value from that function.你很接近,你只需要从 function 返回值。

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

See example 5# here参见示例 5# 这里

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: Output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM