我有一个名为
的函数chewbacca() {
include('external.php');
echo $lang[1];
...
}
文件external.php包含所有$ lang数组。但是,由于我必须执行该函数数千次,我想只包含一次该文件。如果我include_once('external.php');在函数之前,如何在我的函数中使用$ lang数组变量而不必在每次使用之前编写“global”?
答案 0 :(得分:2)
也许把它作为一个论点传递?
<?php
include 'external.php';
function chewbacca($lang_array){
echo $lang_array[1];
//...
}
编辑:
您也可以执行以下操作:
在external.php上:
<?php
return array(
'foo',
'foobar',
'bar',
);
关于index.php:
<?php
function chewbacca($lang_array){
echo $lang_array[1];
//...
}
$foo = include 'external.php';
chewbacca($foo);
EDIT2:
当然现在你可以使用include_once
,但我建议使用require_once
,因为如果include
失败并且脚本应该以错误停止,你将不会拥有该数组。
答案 1 :(得分:1)
除非我误解了你所追求的内容,否则你不需要在每次使用之前写global
,你只需要在函数开始时使用它。
include('external.php');
chewbacca() {
global $lang;
echo $lang[1];
...
}
答案 2 :(得分:1)
简单地说,你不能......
您有几种方法可以做到这一点:
方式#1
global $lang;
include('external.php')
function chewbacca(){
global $lang;
echo $lang[1];
}
方式#2
function chewbacca(){
include('external.php')
echo $lang[1];
}
方式#3
function chewbacca(){
static $lang;
if(!is_array($lang)){ include('external.php'); }
echo $lang[1];
}
方式#4
include('external.php')
function chewbacca($lang){
echo $lang[1];
}
chewbacca($lang);
祝你好运
PS:另一种方法是使用CLASS a在类中创建时(在构造函数内)加载类中的字符串并从$ this-&gt; lang中访问语言字符串...
答案 3 :(得分:1)
静态类也是一种解决方案。
class AppConfiguration {
static $languages = array(
'en' => 'English'
);
}
function functionName($param) {
$lang = AppConfiguration::$languages;
}
require_once文档中的那个类就是它。
答案 4 :(得分:0)
如果我理解正确,请在使用之前尝试将其传递到本地范围;这样你只需要在函数内部使用全局范围。