0

A rather cryptic title, but it's difficult to phrase.

Say I have an object from mysql_fetch_object(). I want to use a getter to return a value from a column.

For example, in a class, we have $this->data. How can I return say $this->data->id (ID column from table) using an argument from the getter function.

This won't work, but something along the lines of:

public function data($key)
{
    return $this->data[$key];
}

Thanks for any help.

3 Answers 3

2

what about return $this->data->$key ?

or if you implement ArrayAccess, return $this->data->$key from the offsetGet() function, then you can use $object[$key] to retrieve the data

Sign up to request clarification or add additional context in comments.

Comments

1

I think what you're searching for are variable variables.

But using mysql_fetch_assoc might be better suited for what you want to do.

Comments

-1

Maybe your looking for __get method ? http://php.net/manual/en/language.oop5.overloading.php Not really sure about what you're looking for.

something like.

public function __get($name) {
    if (array_key_exists($name, $this->data)) {
        return $this->data[$name];
    }

    return null;
}

Now you can access your data as $obj->key

1 Comment

$this->data is an object, if you want to work with it like with an array, you have to cast it to array first. In your case array_key_exists($name, (array) $this->data)

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.