将字符串连接到对象方法

时间:2015-12-15 11:23:51

标签: php object

我有

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

但在{$with}之后,所有内容都为空。

2 个答案:

答案 0 :(得分:1)

只需在键盘上循环调用with方法,
假设$key在数组中,或者您可以将其放在一个数组中。

$produse = $this->$table

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

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

答案 1 :(得分:0)

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

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