1

これはしばらくの間私を悩ませてきたものであり、今日、まともな答えが見つからなかったので、共有したいと思った比較的簡単な解決策を見つけました.

DB ラッパー用に次のコードがあります。

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

    return (object) $results;
}

だから私はできる:

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

しかし、その新しい結果にメソッドを割り当てることができる必要があります。この場合to_json

4

1 に答える 1

1

次のように行うことができます。

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);
    }
}

戻る代わりに、次のようにreturn (object) $resultします。return new Result($result);

$result = DB::find(1);
echo $result->name;      #=> Hello world
echo $result->to_json(); #=> {"name":"Hello world","content":"Hello World!"}
于 2012-11-05T16:31:32.203 に答える