php在一系列函数中全局包含文件
我正在编写一个模板,它将有一系列函数,其中几个将访问同一个包含文件,该文件访问一系列类。我的想法是php在一系列函数中全局包含文件,php,function,include,Php,Function,Include,我正在编写一个模板,它将有一系列函数,其中几个将访问同一个包含文件,该文件访问一系列类。我的想法是 <?php require_once("myfile.php"); $db = new classthing(); function1(){ return $db->afunction; } function2() { return $db->anotherfunction; } PHP函数中的在其自身范围内起作用。 在您的情况下,您可以采
<?php
require_once("myfile.php");
$db = new classthing();
function1(){
return $db->afunction;
}
function2() {
return $db->anotherfunction;
}
PHP函数中的
在其自身范围内起作用。
在您的情况下,您可以采取以下几种方式:
a) 将$db实例作为函数参数传递:
require_once("myfile.php");
$db = new Classthing();
function1(Classthing $db){
return $db->afunction;
}
$a = function1($db); // invocation
b) 使用global
关键字从全局范围访问变量:
require_once("myfile.php");
$db = new Classthing();
function1(){
global $db;
return $db->afunction;
}
$a = function1(); // invocation
$db是一个全局变量。如果您想在PHP中访问函数中的全局变量,您需要用“global”声明它。另外,我不确定您到底想要实现什么,但是如果您想要返回带有函数的方法,您应该使用引用
以下是它应该如何工作:
function &function1(){
global $db;
return $db->afunction;
}