【问题标题】:PHP Mobile Detect WordpressPHP 移动检测 Wordpress
【发布时间】:2013-02-22 07:19:36
【问题描述】:

我在 Wordpress 安装中使用 Serbanghita's PHP Mobile Detect 类。我的 header.php 文件中有以下内容:

<?php
include 'php/Mobile_Detect.php';
$detect = new Mobile_Detect();
?>

当我将以下内容放在我的 single.php 文件中时,我收到一个关于非对象错误的调用:

<?php if ($detect->isMobile()) {
       //Do something
} ?>

有什么想法吗?我无法将包含移动到我的 single.php 文件中,因为我需要在 header.php 中使用它,当然我不能将它复制到 single.php 文件中,因为那时我正在重新声明该类。

任何帮助,非常感谢。

【问题讨论】:

标签: php wordpress class


【解决方案1】:

$detect 变量在文件 single.php 的范围内不可用。

要么使用global $detect,要么首先通过调用$detect = new Mobile_Detect(); 来定义$detect

尽管我应该警告你,污染全局范围很容易出现错误,并且强烈建议不要这样做。至少尽量减少全局变量的数量(例如,在类中包装功能?),使用唯一的名称(例如,为其添加前缀),甚至更好地使用工厂类等高级技术。

【讨论】:

  • 答案是首先使 $detect 成为全局变量(用于所有各种 php 文件)。
  • 然后在子模板的顶部添加&lt;?php global $detect ?&gt;...还要注意还有一个wordpress插件wordpress.org/extend/plugins/wp-mobile-detect
猜你喜欢
  • 2011-04-18
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多