问题描述:

Im using Serbanghita's PHP Mobile Detect class in a Wordpress install. I have the following inside my header.php file:

<?php

include 'php/Mobile_Detect.php';

$detect = new Mobile_Detect();

?>

When I place the following inside my single.php file I get a call on a non-object error:

<?php if ($detect->isMobile()) {

//Do something

} ?>

Any ideas? I can't move the include to my single.php file because I need to use it in header.php and of course I cant copy it into the single.php file because then Im redclaring the class.

Any help, much appreciated.

网友答案:

The $detect variable is not available in the scope of the file single.php.

Either use global $detect or first define $detect by calling $detect = new Mobile_Detect();

All though I should warn you that polluting the global scope is very prone to bugs and strongly discouraged. At least try to minimise the amount of global variables (eg. wrap functionality in a class?), use an unique name (eg. prefix it) or even better use advanced techniques like factory class.

相关阅读:
Top