0

I'm using Wordpress with a custom theme.

At the top of the header.php of the theme I've got a Mobile Detect script.

require_once '/extras/Mobile_Detect.php';
$detect = new Mobile_Detect;

Then further down the header.php page I have a line that checks if the user is on a Mobile, and displays different content accordingly.

if ($detect->isMobile()) { echo "Premium"; } else { echo variable('prem_no'); }

However, in a further included PHP file further down the page, when I try to use the same script:

if ($detect->isMobile()) { echo "Find a psychic"; } else { echo "Our Psychic Readers"; }

I get this error:

Fatal error: Call to a member function isMobile() on a non-object in C:\wamp\www\clairvoyant\extras\reader-categories.php on line 1

How can I make it so that a file required or included in the header.php file, can be referenced to throughout the rest of the page files?

I'm a bit confused between include, include_once, require and require_once, so can someone help clear that up?

Lee
  • 4,187
  • 6
  • 25
  • 71

2 Answers2

2

Not too many differences between require and include but the main point is with require the file must exist or you get an error while include is optional.

and the _once is to make sure you don't include it more than once.


However, in a further included PHP file further down the page, when I try to use the same script I get this error...

This sounds like $detect is not the same object for example

require_once '/extras/Mobile_Detect.php';
$detect = new Mobile_Detect;
if ($detect->isMobile()) { echo "Premium"; }//Good
....
$detect['mobile'] = 'iPhone';
if ($detect->isMobile()) { echo "Find a psychic"; }//Bad
meda
  • 45,103
  • 14
  • 92
  • 122
  • That doesn't make any difference, the error is still produced. And it doesn't say in the guide to use the parentheses (https://github.com/serbanghita/Mobile-Detect/wiki/Code-examples) – Lee Jul 17 '14 at 12:53
  • Parentheses are optional in PHP for non-parameterized constructors, http://stackoverflow.com/q/1945989/231316 – Chris Haas Jul 17 '14 at 13:18
  • @LeeCollings how about using `include '/extras/Mobile_Detect.php';` instead of `require_once` – meda Jul 17 '14 at 14:17
0

My guess is that somewhere along the lines $detect is being reset to something else. Do a search for all instances of $detect and look for something that's using a single equals instead of a double or triple. It could also be another include somewhere that's resetting it.

If the variable $detect flat out didn't exist you would have received a different notice, Undefined variable: detect.

If $detect were a valid object but the method no longer existed you would have received Fatal error: Call to undefined method Mobile_Detect::isMobile.

However your error says that the variable that you are working with is not an object and therefor can't have a member function in the first place.

Chris Haas
  • 53,986
  • 12
  • 141
  • 274