PDO PHP Fetch Class

后端 未结 4 1656
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 07:08

I am learning pdo in php , so as to make database access easier and more efficient .One explanation i have read for fetch _class is that The properties of your object are s

4条回答
  •  醉话见心
    2020-11-28 07:23

    This means that when using PDO to return a result into a custom object, you are required to set out the member variables which correspond to the query result keys.

    such as:

    class User
    {
        //Predefine Here
        public $id;
        public $username;
        public $password;
        public $email;
        public $hash;
    
        public function profileLink()
        {
             return sprintf('%s',$this->id,$this->username);
        }
    }
    
    $result = $sth->fetchAll(PDO::FETCH_CLASS, "User");
    foreach($result as $user)
    {
        echo $user->profileLink();
    }
    

    This way PDO can set the variables to the object outside of its internal scope.

    if you user class was like so:

    class User
    {
    }
    

    then PDO Would not be able to set the values from outside the scope, as there are no properties defined.

提交回复
热议问题