未定义变量:窗口在我的脚本


Undefined variable: window in my script?

我有这个错误:

PHP通知- yii'base' errorrexception

未定义变量:window

函数inViewport($el) {

部分代码:

<?php
$lazyload = <<< JS
$(function() {
  var $window = $(window),
      images = [],
      imagesToBeLoaded = 0,
      i,
      src;
  function throttle(func, wait) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      if(!timeout) {
        timeout = setTimeout(function() {
          timeout = null;
        }, wait);
        func.apply(context, args);
      }
    };
  }
  function inViewport($el) {
    var top = $window.scrollTop(),
        left = $window.scrollLeft(),
        bottom = top + $window.height(),
        right = left + $window.width(),
        offset = $el.offset(),
        thisTop = offset.top,
        thisLeft = offset.left,
        thisBottom = thisTop + $el.outerHeight(),
        thisRight = thisLeft + $el.outerWidth();
                      ...
JS;
$this->registerJs($lazyload, View::POS_READY);
?>

为什么会出现这个错误?codepen

引用heredoc的名称,以防止PHP将$window解释为变量:

<?php
$lazyload = <<< 'JS'
...
JS;

(见http://php.net/manual/en/language.types.string.php language.types.string.syntax.nowdoc)