php - 公共函数返回 NULL 而不是数组
问题描述
我正在尝试围绕 pdo mysql 编写一个瘦包装器,但我遇到了一个公共函数返回 null 而不是预期的关联数组数组的问题。这是按值/引用传递的问题吗?我最初的想法是这是一个参考或公共问题,但这个简单的例子有效。
<?php
class PDOMysqlAdapter {
public $db;
public $result;
public $test = array(1,2);
public function get(){
return $this->test;
}
public function __construct($host, $port, $dbname, $username, $password, $charset = "utf8") {
$this->db = new PDO(
"mysql:host={$host};port={$port};dbname={$dbname};charset={$charset}",
$username,
$password
);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function singleton($sql, $debug = false) {
if($debug) { error_log("Executing:\n\n{$sql}\n"); }
try {
$this->result = $this->db->query($sql)->fetch(PDO::FETCH_ASSOC);
if($debug) { error_log(print_r($this->result, true)); }
return $this->result;
} catch(PDOException $ex) {
error_log($ex->getMessage()."\n");
return NULL;
}
}
public function multiple($sql, $debug = false) {
if($debug) { error_log("Executing:\n\n{$sql}\n"); }
try {
$this->result = $this->db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
if($debug) { error_log(print_r($this->result, true)); }
error_log(count($this->result));
return $this->result;
} catch(PDOException $ex) {
error_log($ex->getMessage()."\n");
return NULL;
}
}
}
$db = new PDOMysqlAdapter(DB_SERVER, DB_PORT, DB_NAME, DB_USER, DB_PASS);
error_log(print_r($db->get(), true)); // does what I think it should
$result = $db->singleton("SELECT 1", true);
error_log(print_r($result, true)); // return { '1' => '1' }
$foo = $db->multiple("SELECT * FROM users LIMIT 2", true); // query returns without error and result exists within scope
error_log(print_r($foo, true)); // null
error_log(count($db->result)); // variable is public and full of expected contents
为什么 $foo 在这里为 NULL?$db->result
包含我希望返回到 $foo 中的东西。
解决方案
推荐阅读
- javascript - 试图为我的不和谐机器人发出抽奖命令,但不断返回未定义的获胜者
- java - Javalin sessionAttribute() 在请求之间不存在
- java - 如何使用 Java 获取在 TextInput/OutputFormat 中创建的配置单元表的架构
- html - 不能只用 AngularJS 代码添加单个数字
- javascript - 问题导入/需要pondjs
- wordpress - 找不到 wordpress 版本或更新
- r - ggplot将颜色代码列与R数据框中的另一列匹配
- clion - 如何防止 CLion 调试成 C++ 源文件
- c# - Windows 窗体,SendMessage 行中的语法错误
- sql-server - 自动在不同文件组中创建索引,编辑发布配置文件脚本