简体   繁体   中英

include php in class and use variable from include

i want to access $mysqli from db_connect.db in my class

db_connect.php

<?php
include_once("db.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
mysqli_set_charset($mysqli,"utf8");
?>

class.php

class class{

    function __construct() {
        include_once 'db_connect.php';
    }

    function get()
    {
        if (!$mysqli->connect_errno) {
    }
    }
}

i can access $mysqli if i include the db_connect.php directly in a php function without a class

edit and i want to access $mysqli in all functions of the class

thanks

you can save it in a class variable:

class class{
    private $mysqli;

    function __construct() {
        include_once 'db_connect.php';

        $this->mysqli = $mysqli;
    }

    function get()
    {
        if (!$this->mysqli->connect_errno) {
        }
    }
}

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