Concatenate string to object method

I have

    $produse = $this->$table->with('categorie')
                             ->with_deleted()
                             ->get_all();

and I need

    foreach ($this->$table->belongs_to as $key => $value):
            $with = $produse->with("$key");
    endforeach;

    $produse = $this->$table{$with}
                             ->with_deleted()
                             ->get_all();

but after {$with} everything is null.

Upvotes: 0

Views: 97

Answers (2)

Alex Andrei
Alex Andrei

Reputation: 7283

Just call the with method in a loop over the keys,
assuming $key is in an array or you can put it in one.

$produse = $this->$table

foreach($array as $key){
    $produse->with($key);
}

$produse->with_deleted()
     ->get_all();

Upvotes: 1

jiboulex
jiboulex

Reputation: 3031

In my opinion, storing function calls in strings is a bad practice. Assuming you can have multiple possibilities for your with method, you should first determine which one you're gonna use :

$withKey = $key;
// if you must use another variable, determine which here, the way depends on your needs

//and then call the function
$produse = $this->$table->with($withKey)
    ->with_deleted()
    ->get_all();

Upvotes: 0

Related Questions