0

所以我有这门课:

class c_user
{
    function __construct($userID)
    {
        dbOpen($db); // open database
        $sq = "select * from users where user_id='".$userID."'";
        $rs = getRS($sq, $db); // query database - simplified
        $this->firstname = $rs['firstname'];
    }
}

我这样使用它:

$user = new c_user(123);
echo $user->firstname;

是否可以将数据作为关联数组访问?像那样:

echo $user['firstname'];

谢谢

4

2 回答 2

3

是的,你只需要让你的类实现ArrayAccess接口。

于 2013-06-12T12:47:31.543 回答
0

这个怎么样?

class c_user 
{
    function __construct($userid)
    {
        $rs = array('firstname'=>'myfirstname');
        $this->firstname = $rs['firstname'];
    }
}

$user = new c_user(123);
//echo $user->firstname;
$user =  (array) $user;
echo $user['firstname'];
于 2013-06-12T13:00:25.103 回答