将字符串连接到对象方法


Concatenate string to object method

我有

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

我需要

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

但在CCD_ 1之后,所有内容都为空。

只需在键上的循环中调用with方法,
假设$key在一个数组中,或者你可以把它放在一个中。

$produse = $this->$table
foreach($array as $key){
    $produse->with($key);
}
$produse->with_deleted()
     ->get_all();

在我看来,将函数调用存储在字符串中是一种糟糕的做法。假设你的with方法有多种可能性,你应该首先确定你要使用哪一种:

$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();