Global object within include of an include
Question
Righty-o
I am fairly new to OOP.
Im using PHP v5+
I have my index.php:
<?
include_once('class/includes.php');
$reg = new register;
$action = $_GET['action'];
$page = $_GET['page'];
include('header.php');
if($page):
include($page);
else:
include('home.php');
endif;
include('footer.php');
?>
i have my htaccess set up so that the url for each page is foo.com/pagename
Thats fine.
on my classes.php page (foo.com/classes) which as default includes viewClasses.php //note classes refers to yoga classes rather than OOP classes
so essentially i have 2 levels of includes (index.php including classes.php which includes viewClass.php)
this is my viewClass.php
<?
global $reg;
$reg->viewClassList();
echo $reg->classList;
?>
For some reason it is not picking up $reg as defined in index.php and therefore is giving me this error:
Fatal error: Call to a member function viewClassList() on a non-object in /home/pandazco/public_html/register/viewClass.php on line 3
I hope this explains my problem well enough...
Solution
The problem appears to be that you are not including the instantiation in your viewClass.php which means that $reg is nothing. This is what the error is telling you.
However I would never use global vars, in fact I am pretty sure there are many lengthy discussions on not using them. Instead I would set a session variable and read from this instead if you need to pass data between different php scripts.
Additionally why are you using $reg as a global anyway? All you appear to do is instantiate it in index.php and try to call it in viewClass.php. What are you trying to achieve exactly?