简单的答案;用这个:
$this->{$this->modelBName}->find('all');
请注意属性名称周围的大括号 {}。更多信息可以在手册中找到;
http://php.net/manual/en/language.variables.variable.php
更清洁的方法可能是一种“工厂”方法;
/**
* Load and return a model
*
* @var string $modelName
*
* @return Model
* @throws MissingModelException if the model class cannot be found.
*/
protected function model($modelName)
{
if (!isset($this->{$modelName})) {
$this->loadModel($modelName);
}
return $this->{$modelName};
}
哪个可以这样使用;
$result = $this->model($this->modelBName)->find('all');
debug($result);
而且,如果您不想指定模型,但希望它自动返回一个 '$this->modelBName';
/**
* Load and return the model as specified in the 'modelBName' property
*
* @return Model
* @throws MissingModelException if the model class cannot be found.
*/
protected function modelB()
{
if (!isset($this->{$this->modelBName})) {
$this->loadModel($this->modelBName);
}
return $this->{$this->modelBName};
}
可以这样使用:
$result = $this->modelB()->find('all');
debug($result);