Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php在一系列函数中全局包含文件_Php_Function_Include - Fatal编程技术网

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;
}