首页 > 解决方案 > 公共函数返回 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 中的东西。

标签: phpoop

解决方案


推荐阅读