简体   繁体   中英

Use external included file inside php functions

I'm writing a functions.php file...now, some functions must access the db. I have a db_connect.php file which contains the connection script. I've included it in functions.php with:

require "sys/db_connect.php";

but how to use the connection script ($con) inside

function a() {
   ...
}
function c() {
   ...
}

and so on? I've tried already setting $con variable as global, but no success.

function a($db) {
   //do something with $db
}
function c($db) {
   //do something with $db
}

$result = a($conn);
$something = c($conn);

There are three ways to do this, either accessing the value using $GLOBALS , declaring it as a global variable or passing it as a parameter

1st way:

include 'db_connect.php';
    function a() {
        $link = $GLOBALS['con'];
        // you can assign $GLOBALS['con'] or use it as a normal variable
    }

2nd way:

include 'db_connect.php';
function a() {
    global $con;
    // then use it as a normal variable
 }

3rd way:

function a($con) {
    // use the variable
}

Read more about variable scopes here

This structure should work. Note where the global declarations appear. I'd normally pass the $con variable into the function as an argument rather than using it as a global , though.

dbconnect.php

<?
$con = mysqli_connect("blah","blah","blah","blah");
?>

functions.php

require('dbconnect.php');
function a() {
  global $con;
   ...
}
function c() {
  global $con;
   ...
}

I do this:

// sys/db_connect.php
<?php
function db(){
  return new mysqli('host', 'username', 'password', 'database');
}
?>

// functions.php
<?php
require 'sys/db_connect.php';
/* you can even close the connection and reopen it this way
   $db = db(); $db->close(); $database = db(); */
function a() {
  $db = db();
}
function c() {
  $db = db();
}
?>

If you have assigned a variable $con in db_connect.php outside any functions as follows:

//----------
//sys/db_connect.php
//----------
$con = 'my connection script'; //You don't need to put global here

Then you can use $con in functions a() and c() in another php file as follows:

//----------
//other_file.php
//----------
require 'sys/db_connect.php';

function a(){
 global $con;   //global allows $con from above to be used in this function a()

 print_r($con); //This line just for testing purposes!
}

function b(){
 global $con;   //global allows $con to be used in this function b()

 print_r($con); //This line just for testing purposes!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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