Reputation: 3473
I have simple PHP code like this:
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\bvh\BvhFiles;
use app\models\bvh\BvhCategories;
class BvhController extends Controller {
public function actionView($id) {
// $cache = $cache = Yii::$app->getCache();
$BvhFile = BvhFiles::getDb()->cache(function ($db) {
return BvhFiles::find()->where(['OR', 'id=' . $id, 'YoutubeId=' . $id])->one();
});
But it's not work. It fails with
PHP Notice – yii\base\ErrorException
Undefined variable: id
at
return BvhFiles::find()->where(['OR', 'id=' . $id, 'YoutubeId=' . $id])->one();
How should I pass $id variable to this code?
Thank you!
Upvotes: 1
Views: 373
Reputation: 25312
You should simply try this :
$BvhFile = BvhFiles::getDb()->cache(function ($db) use ($id) {
return BvhFiles::find()->where(['OR', 'id=' . $id, 'YoutubeId=' . $id])->one();
});
Read more about anonymous function and how to use variables from the parent scope.
And you should use this (read more) :
return BvhFiles::find()->where(['OR', ['id' => $id], ['YoutubeId' => $id]])->one();
Upvotes: 2
Reputation: 25435
That's a problem not related to Yii, but to php itself. If you want to pass a variable down to an anonymous function you need to use the use
keyword:
$BvhFile = BvhFiles::getDb()->cache(function ($db) use($id) {
return BvhFiles::find()->where(['OR', 'id=' . $id, 'YoutubeId=' . $id])->one();
});
Upvotes: 1