PHP passing model as a function argument <p>I'm using the Laravel Framework and I've got <code>MyModel</code>.</p> <pre><code>namespace App\Models; use Illuminate\Support\Facades\DB; class MyModel extends \Eloquent { //Some stuff goes here } </code></pre> <p>I have made this function that group the data of an array. <strong>This is working well.</strong></p> <pre><code>public static function GroupBy($array, $key){ $grouped = array(); foreach($array as $arr){ if(!array_key_exists($arr-&gt;MyModel['id'], $grouped)){$grouped[$arr-&gt;MyModel['id']] = array();} array_push($grouped[$arr-&gt;MyModel['id']], $arr[$key]); } return $grouped; } </code></pre> <p><strong>Now I wish to make this function more generic by passing the model by which my grouping is made. In order word I'd like to be able to pass <code>MyModel['id']</code> as another argument.</strong> Something like:</p> <pre><code>$by = "MyModel['id']"; public static function GroupBy($by, $array, $key){ $grouped = array(); foreach($array as $arr){ if(!array_key_exists($arr-&gt;$by, $grouped)){$grouped[$arr-&gt;$by] = array();} array_push($grouped[$arr-&gt;$by], $arr[$key]); } return $grouped; } </code></pre> <p>This last solution doesn't work. It returns me an array with an array containing all the <code>id</code>.</p>