PHP-Yii2变量作用域


PHP - Yii2 variable scope

我有这样的简单PHP代码:

<?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();
        });

但这行不通。失败

PHP通知–yii''base''ErrorException

未定义的变量:id

 return BvhFiles::find()->where(['OR', 'id=' . $id, 'YoutubeId=' . $id])->one();

我应该如何将$id变量传递给此代码?

谢谢!

您应该简单地尝试一下:

$BvhFile = BvhFiles::getDb()->cache(function ($db) use ($id) {
    return BvhFiles::find()->where(['OR', 'id=' . $id, 'YoutubeId=' . $id])->one();
});

阅读有关匿名函数以及如何使用父作用域中的变量的更多信息。

你应该使用这个(阅读更多):

return BvhFiles::find()->where(['OR', ['id' => $id], ['YoutubeId' => $id]])->one();

这个问题与Yii无关,而是与php本身有关。如果要将变量传递给匿名函数,则需要使用use关键字:

$BvhFile = BvhFiles::getDb()->cache(function ($db) use($id) {
    return BvhFiles::find()->where(['OR', 'id=' . $id, 'YoutubeId=' . $id])->one();
});