在传递引用中将PHP变量设置为类成员失败


Setting PHP variable to class member in a Pass-By-Reference Fails

我通过引用类方法传递一个变量,目的是将其设置为同一类的成员(基于函数的选择器)。虽然这似乎没有违反PHP不推荐使用的调用时间传递引用的规则,但我一定遗漏了一些内容,因为它不起作用。

我简化了我的代码来说明这个问题:

<?php
class Database
{
    static $USER_TABLE = 1;
    static $INVOICE_TABLE = 2;
    static $PRODUCT_TABLE = 3;
    var $users;
    var $invoices;
    var $products;
    function __construct()
    {
        $this->users []= array ('id'=>0, 'first_name'=>'John', 'last_name'=>'Doe');
        $this->products []= array('id'=>0, 'user_id'=>'0', 'printer'=>'HP','computer'=>'Toshiba');
        $this->invoices []= array('id'=>0, 'user_id'=>'0', 'total_items'=>2, 'total_cost'=>700);
    }
    function getTable($table_name, &$table)
    {
        switch ($table_name)
        {
            case Database::$USER_TABLE: $table = $this->users; break;
            case Database::$INVOICE_TABLE: $table = $this->invoices; break;
            case Database::$PRODUCT_TABLE: $table = $this->products; break;
        }
    }
    function addEntry($table_name, $info_array)
    {
        $this->getTable($table_name, $table); // THIS FAILS!  WHY?
        //$table = &$this->users; // THIS WORKS
        if ($table !== null)
        {
            $id = 0;
            if (count($table))
                $id = ((int)$table[count($table)-1]['id'])+1;
            $entry['id'] = $id;
            foreach ($info_array as $k => $v)
            {
                $entry [$k]= $v;
            }
            $table []= $entry;
        }
    }
}
$db = new Database;
$db->addEntry(Database::$USER_TABLE, array('first_name'=>'Jane', 'last_name'=>'Plain'));
var_dump($db);
?>

另一种选择是从getTable(…)中取出switch用例,并将其粘贴到我所有调用它的函数的顶部,但这种类型的代码重复是不可取的。

任何见解都值得赞赏!

getTable实际返回一个表会容易得多:

function getTable($table_name)
{
    switch ($table_name)
    {
        case Database::$USER_TABLE: return $this->users; break;
        case Database::$INVOICE_TABLE: return $this->invoices; break;
        case Database::$PRODUCT_TABLE: return $this->products; break;
    }
}

然后只需调用以下命令:

$table = $this->getTable($table_name);