PHP避免在函数内部使用全局

时间:2013-06-17 08:41:30

标签: php

如何避免使用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
}

2 个答案:

答案 0 :(得分:6)

这就是你使用的课程。例如,您可以轻松扩展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)));
        }
    }
?>

如果您希望保持两个逻辑分离,这也是非常可能的。

您将类变量$conn引用的数据库(来自类本身)引用为$this->conn。如果您想在课堂外使用此变量,则必须将private $conn变为public $conn,然后您可以使用$db = new DB(); $db->conn->prepare(/*etc*/);来引用它:

<?php
    class DB {
        const PASSWORD_SALT = "abc123";

        private $conn;

        public function __construct() {
            $this->conn = new mysqli("localhost", "foo", "bar", "foobar");
        }

        public function AddUser($username, $password) {
            $addUser = $this->conn->prepare("INSERT INTO `users` (`username`, `password`) VALUES (:username, :password)");
            $addUser->execute(array(":username" => $username, ":password" => md5(self::PASSWORD_SALT . $password)));
        }
    }
?>

答案 1 :(得分:1)

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

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