Re: How to access one class from another

From: Date: Fri, 10 Sep 2004 20:40:44 +0000
Subject: Re: How to access one class from another
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-196355@lists.php.net to get a copy of this message
"Brent Baisley" <brent@landover.com> wrote in message news:398AE38E-0367-11D9-9E60-000A95CD828E@landover.com... > What is the best way to access one class from another? What I have is a > couple of "core" classes that are loaded into instances at the start of > each page. I then load instances of page specific classes. How would I > access the already loaded instances of the core classes from inside one > of the page specific classes? > > I tried a few things that didn't work. Is the only way to do this is to > load another instance of the core classes? > I'm finally trying to really get my hands around OOP, which has gone > very smooth up until this instance:). I'm using v4 not v5. > > I'm looking for something like this: > class Lists { > function UserList() { > } > ... > } > $coreLists = new Lists(); > ... > class Data { > function Entry() { > $users = $coreLists->UserList(); file://Accessing Lists Class > ... > } > } Hi Brent, this is a case of variable scope: http://de2.php.net/variables.scope There are different ways to solve your problem: 1. Declare $coreLists global in your method: function Entry() { global $coreLists; $users = $coreLists->UserList(); } 2. Access it via the superglobal $GLOBALS: function Entry() { $users = $GLOBALS['coreLists']->UserList(); } 3. Pass the variable it to the class constructor and assign it to a class property: var $coreLists; function Data($coreLists) { $this->coreLists = $coreLists; } Best regards, Torsten Roehr

« previous php.general (#196355) next »