我在使用PHP的OOP上刷新自己,我看到了将函数和/或变量设置为静态的示例.我何时以及为什么要将变量/函数设置为静态?我已经完成了其他语言,并且不记得曾经使用静态,我从来没有找到真正的目的.我知道它的作用,但为什么不只是使用变量呢?
我正在尝试使用PHP session_set_save_handler,我想使用PDO连接来存储会话数据.
我有这个函数作为写操作的回调:
function _write($id, $data) {
logger('_WRITE ' . $id . ' ' . $data);
try {
$access = time();
$sql = 'REPLACE INTO sessions SET id=:id, access=:access, data=:data';
logger('This is the last line in this function that appears in the log.');
$stmt = $GLOBALS['db']->prepare($sql);
logger('This never gets logged! :(');
$stmt->bindParam(':id', $id, PDO::PARAM_STR);
$stmt->bindParam(':access', $access, PDO::PARAM_INT);
$stmt->bindParam(':data', $data, PDO::PARAM_STR);
$stmt->execute();
$stmt->closeCursor();
return true;
} catch (PDOException $e) {
logger('This is never executed.');
logger($e->getTraceAsString());
}
}
Run Code Online (Sandbox Code Playgroud)
前两条日志消息总是显示出来,但是后面的第三条消息永远$stmt = …
我有一个数据库类,它的实例在主宣布index.php为
$db = new Database();
Run Code Online (Sandbox Code Playgroud)
有没有办法让$db变量在所有其他类中被全局识别而不必声明
global $db;
Run Code Online (Sandbox Code Playgroud)
在每个类的构造函数中?
我正在尝试创建一个简单的使用单例类连接到mysql数据库并进行查询,代码工作正常,我没有遇到任何问题,但因为我是OOP的新手,我想知道这是否是不好的做法.
这是班级
class Database {
private $databaseName = 'dbname';
private $host = 'localhost';
private $user = 'user';
private $password = 'pass';
private static $instance; //store the single instance of the database
private function __construct(){
//This will load only once regardless of how many times the class is called
$connection = mysql_connect($this->host, $this->user, $this->password) or die (mysql_error());
$db = mysql_select_db($this->databaseName, $connection) or die(mysql_error());
echo 'DB initiated<br>';
}
//this function makes sure there's only 1 instance of the Database class
public static …Run Code Online (Sandbox Code Playgroud)