是否可以将mysqli_connect对象定义为常量

时间:2019-05-27 10:51:27

标签: php mysqli

我只是想让我的生活更轻松。我的问题(而且我知道解决该问题的方法)是我无法从函数直接访问mysqli_connect对象,该函数必须将对象作为参数传递。

define_constant( MYSQLI , mysqli_connect( "localhost","my_user","my_password","my_db" ) );

当前的操作类似于:

$link = mysqli_connect("localhost","my_user","my_password","my_db");

function doSqlStuff( $link ){
    //Run my sql statments here using the link passed through the fuction
    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com')";

    if ($link->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $link->error;
    }
}
doSqlStuff( $link );

我希望以更简单的方式打电话

define_constant( MYSQLI , mysqli_connect("localhost","my_user","my_password","my_db") );

function doSqlStuff(){
    //Run my sql statments here using the link as a constant
    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com')";

    if (MYSQLI->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . MYSQLI->error;
    }
}
doSqlStuff();

我的总体感觉是,这是一个坏主意。但是,这会使我的生活更轻松,并且我无法想到不这样做的原因。

这行得通吗,或者有类似的方法可以解决访问mysqli连接而不必每次都传递对象的窍门。

1 个答案:

答案 0 :(得分:0)

实际上,您不能使用常量来存储非静态数据。但是您可以创建单例类型的类来访问您的连接链接。

<?php

class Connection
{
    private static $link;

    static public function link() {
        if (self::$link === null) {
            self::$link = mysqli_connect( "localhost","my_user","my_password","my_db" );
        }

        return self::$link; 
    }
}

function doSqlStuff(){
    //Run my sql statments here using the link as a constant
    $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";

    if (Connection::link()->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . Connection::link()->error;
    }
}