PHP避免在函数中使用全局

PHP避免在函数中使用全局,php,Php,如何避免使用global访问php函数中的变量。我知道我可以将它们存储为常量,但我的变量包含sql,而且很多。像这样 $selectSql = 'select name from table where name = :thisName' and year = :thisYear; $selectSqlBind = array(":thisName" => $thisName,":thisYear" => $thisYear); 以下是我目前的做法 function myFunct

如何避免使用
global
访问php函数中的变量。我知道我可以将它们存储为常量,但我的变量包含sql,而且很多。像这样

$selectSql = 'select name from table where name = :thisName' and year = :thisYear;
$selectSqlBind = array(":thisName" => $thisName,":thisYear" => $thisYear);
以下是我目前的做法

function myFunction (){
global $selectSql;
global $selectSqlBind;

$addUser = $conn->prepare($selectSql);
$addUser->execute($selectSqlBind);
//Other Stuff goes on
}
我也能做到

function myFunction ($selectSql,$selectSqlBind){
$addUser = $conn->prepare($selectSql);
$addUser->execute($selectSqlBind);
//Other Stuff goes on
}
function myFunction (){
$addUser = $conn->prepare($selectSql);
$addUser->execute($selectSqlBind);
//Other Stuff goes on
}
但是我该怎么办呢

function myFunction ($selectSql,$selectSqlBind){
$addUser = $conn->prepare($selectSql);
$addUser->execute($selectSqlBind);
//Other Stuff goes on
}
function myFunction (){
$addUser = $conn->prepare($selectSql);
$addUser->execute($selectSqlBind);
//Other Stuff goes on
}

您应该为此使用函数参数,因此传递查询和绑定参数


但是,数据库连接本身应该通过其他方法获得。请仔细查看一些PHP框架以及它们如何解决这个问题,或者阅读设计模式,如注册表模式或依赖项注入容器等。

您应该为此使用函数参数,因此请传递查询和绑定参数


但是,数据库连接本身应该通过其他方法获得。请仔细看看一些PHP框架以及它们是如何解决这个问题的,或者阅读一些设计模式,如注册表模式或依赖项注入容器等。

这就是使用类的目的。例如,您可以轻松地扩展MySQLi类,保留所有功能,但添加自己的功能。然后您可以简单地通过
$this
而不是
$conn
引用MySQLi语句:

<?php
    class DB extends mysqli {
        const PASSWORD_SALT = "abc123";
        public function AddUser($username, $password) {
            $addUser = $this->prepare("INSERT INTO `users` (`username`, `password`) VALUES (:username, :password)");
            $addUser->execute(array(":username" => $username, ":password" => md5(self::PASSWORD_SALT . $password)));
        }
    }
?>

这就是您使用类的目的。例如,您可以轻松地扩展MySQLi类,保留所有功能,但添加自己的功能。然后您可以简单地通过
$this
而不是
$conn
引用MySQLi语句:

<?php
    class DB extends mysqli {
        const PASSWORD_SALT = "abc123";
        public function AddUser($username, $password) {
            $addUser = $this->prepare("INSERT INTO `users` (`username`, `password`) VALUES (:username, :password)");
            $addUser->execute(array(":username" => $username, ":password" => md5(self::PASSWORD_SALT . $password)));
        }
    }
?>

是什么阻止你使用参数?你可能在寻找一个类,它正好解决了这类问题。是什么阻止你使用参数?你可能在寻找一个类,它正好解决了这类问题。