使用像关联数组的php类对象

时间:2013-06-12 12:46:33

标签: php class associative-array

所以我正在上课:

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'];

感谢

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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'];