简体   繁体   English

在类中包含 php 并使用 include 中的变量

[英]include php in class and use variable from include

i want to access $mysqli from db_connect.db in my class我想从班级中的 db_connect.db 访问 $mysqli

db_connect.php 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类.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如果我将 db_connect.php 直接包含在没有类的 php 函数中,我可以访问 $mysqli

edit and i want to access $mysqli in all functions of the class编辑,我想在类的所有函数中访问 $mysqli

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) {
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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