1

This is something that has been bugging me for a while and today I found a relatively easy solution that I thought I'd share as I couldn't seem to find any decent answer.

I have this code for my DB wrapper:

function find($id) {
    //Fetch the results
    //Put the results into an array

    return (object) $results;
}

So I could do:

$result = DB::find(1);
echo $result->name; #=> Hello world

But I need to be able to assign methods to that new result. In this case to_json

7
  • why cant you just pass $result to json_encode? Commented Nov 5, 2012 at 16:50
  • This isn't about the to_json function. It's about being able to implement functions that the $results variable can use. Commented Nov 5, 2012 at 16:52
  • That was a crappy explanation sorry. For example you could implement this in future: pastebin.com/swuf3rEi The save() function would not have been previously possible. Commented Nov 5, 2012 at 16:54
  • there is no sane way of adding methods to an instance in PHP. If you need a save or toJson or whatever method, write a class. Commented Nov 5, 2012 at 16:57
  • Which I did.. read the answer :p Commented Nov 5, 2012 at 16:57

1 Answer 1

1

You can do so like this:

class Result {
    protected $results;

    public function __construct($results) {
        $this->results = $results;

        foreach($results as $key => $value) {
            $this->$key = $value; 
        }
    }

    public function to_json() {
        return json_encode($this->results);
    }
}

Now instead of returning return (object) $result just do: return new Result($result);

$result = DB::find(1);
echo $result->name;      #=> Hello world
echo $result->to_json(); #=> {"name":"Hello world","content":"Hello World!"}
Sign up to request clarification or add additional context in comments.

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.