2

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

2
  • You should start your class with an upper case letter, in this case: User Commented Aug 3, 2012 at 13:19
  • Note that PHP/5.4.0 and later support array dereferencing, so echo $user->getUser()['icon']; is now valid syntax and will do what you expect. Commented Aug 3, 2012 at 13:39

3 Answers 3

1

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;
Sign up to request clarification or add additional context in comments.

Comments

1

Try the following :

print_r ($user->getUser);

If that returns an array, try it like this :

echo $user->getUser['icon'];

Comments

1

You should use it this way:

$userobj = new User();
$user = $userobj->getUser();

Now you have the fetched data in the $user variable and may output it at will:

echo $user['icon'];

My example should work with your existing code, and if you want to change the values in the future of the users, you just change the key in the echo statement: echo $user['someothervalue'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.