dongyi9783 2012-08-03 13:17
浏览 56
已采纳

PHP OOP返回并调用单个数组值

I'm in the process of learning to use OOP in php, I'm having a few issues with what is probably a really simple solution that I'm just not using the right search terminology to find.

I have my class

class user {

    function getUser() {

        if ($_SESSION['status'] == "authorized") {

            $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

            $sql = "SELECT * FROM users WHERE username = :username";

            $st = $conn->prepare( $sql );

            $st->bindValue( ":username", $_SESSION['usernames'], PDO::PARAM_STR );

            $st->execute();

            $row = $st->fetch();

            $conn = null;

            return $row;

        }
    }
}

and then in my template file i'm calling the following

$user = new user();
echo $user->getUser->icon;

hopefully the bottom line shows what i'm trying to call, basically in the sql results I'm after just calling $row['icon']; directly from the return array.

is this possible? if so could someone point out the terminology i'm missing

Thanks in advance

  • 写回答

3条回答 默认 最新

  • dongxie3352 2012-08-03 13:20
    关注

    If you are going to keep using that object I would do the following:

    class user {
        public $icon;
    
        function getUser() {
    
        if ($_SESSION['status'] == "authorized") {
    
            $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    
            $sql = "SELECT * FROM users WHERE username = :username";
    
            $st = $conn->prepare( $sql );
    
            $st->bindValue( ":username", $_SESSION['usernames'], PDO::PARAM_STR );
    
            $st->execute();
    
            $row = $st->fetch();
    
            $conn = null;
    
            $this->icon=$row;
    
        }
        }
    }
    

    Then you can use:

    echo $user->icon;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 需求高精度PT100设计电路和算法
  • ¥15 单片机配网,继电器开关,广播
  • ¥60 Qcustomplot绘制实时动态曲线
  • ¥20 运用matlab画x-y图
  • ¥15 用idea运行项目,运行tomcat报错:断言失败
  • ¥15 Sqlserver查询链接服务器数据问题
  • ¥15 Bibtex4Word 引用中文文献
  • ¥20 用opencv c/c++ 转换成灰度图,然后做一下直方图均衡,输出mp4文件
  • ¥20 matlab中的双层数值积分
  • ¥50 服务器打印水晶报表问题