gpt4 book ai didi

php - 从 php 中的另一个类访问变量作为对象

转载 作者:行者123 更新时间:2023-11-29 22:55:30 25 4
gpt4 key购买 nike

您好,我正在尝试访问从 Database 类中的 DatabaseConnection 类返回的 pdo 对象,但使用单例模式给我带来了困难。请帮助

class DatabaseConnection {
protected static $_instance = NULL;
public static $pdo;
private function __construct() {
try {
$this->pdo = new PDO ( 'mysql:host=' . Configuration::getConfiguration ( 'mysql/host' ) . ';dbname=' . Configuration::getConfiguration ( 'mysql/databaseName' ), Configuration::getConfiguration ( 'mysql/user' ), Configuration::getConfiguration ( 'mysql/password' ) );
} catch ( PDOException $e ) {
echo 'woops !connection to the server failed.' . $e->getMessage ();
}
}


public static function getConnectionInstance() {
if (! isset ( self::$_instance )) {
self::$_instance = new DatabaseConnection ();
}
return self::$_instance;
}
}/*end od DatabaseConnection*/



class Database implements DatabaseInterface {
public static function select($fields = array(), $table, $where = array())
{
$fields = '`' . implode ( '`,`', $fields ) . '`';
$fix = '';
$x = 1;
foreach ( $where as $tableField => $value ) {
$fix .= "`{$tableField}` = '{$value}'";
if ($x < count ( $where )) {
$fix .= ' AND ';
}
$x ++;
}
$sql = "SELECT {$fields} FROM `{$table}` WHERE {$fix} ";
if (DatabaseConnection::$pdo->prepare ( $sql )) {
echo 'prepared';
}
return false;
}
}

最佳答案

$pdo 成员应该是instance 成员,而不是class 成员。仅将 public static $pdo 更改为 public $pdo。然后您可以通过以下方式访问PDO实例

DatabaseConnection::getConnectionInstance()->pdo;

关于php - 从 php 中的另一个类访问变量作为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28732870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com