Re: Class instantiation within another class?
| From: | Jesse Swensen | Date: | Sat, 17 Jun 2000 12:52:02 +0000 |
| Subject: | Re: Class instantiation within another class? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-2128@lists.php.net to get a copy of this message | ||
I believe you almost have it. Lets look at the following:
class class#1 {
function method() {
$class2 = new class#2;
}
}
class class#2 {
function print_me() {
print "Class #2 Print Me";
}
}
Now, if we look at the class#1 function method the variable we are storing
the object reference in is a local variable to function method. It can't be
referenced outside of method. (Can't is a strong word. Maybe add "without
some extra work".)
So, if we want to make the object reference available, one thing we could do
is change it's scope. So, lets modify class#1 to look like:
class class#1 {
function method() {
$this->class2 = new class#2;
}
}
Now it is a instance variable. Now we can do the following:
$class1 = new class#1
$class1->method();
$class1->class2->print_me();
and we should get the output: Class #2 Print Me
Hope this helps...
--
Jesse Swensen
swensenj@bellsouth.net
> From: Thomas Reinke <reinke@e-softinc.com>
> Organization: E-Soft Inc.
> Date: Fri, 16 Jun 2000 22:10:05 -0400
> To: php-general@lists.php.net
> Subject: [PHP-GENERAL] Class instantiation within another class?
>
> Can anyone point out the problem with this logic:
>
> include class#1
> include class#2
>
> $class1 = new class1;
> $class1->method();
>
> And within class1's "method" call, it does a
> "$class2 = new class2"
>
> I've not been able to get this to work, and am wondering
> if there is a fundamental limitation to making use of
> one class from within another. Essentially, I don't
> think it is recognizing the 2nd class, and this shows
> up when i attempt to do a "class2->method()" call.
> (Says no such beast exists). If, on the other hand,
> I instantiate both classes first, and then pass class2
> as a parameter to class1 in the constructor, I have no
> problem accessing class2's methods...
>
> I'd thought it was something perhaps with the "global"
> declaration, but haven't been able to figure out how
> to "global"ly declare the class itself, prior to
> instantiation.
>
> Any ideas?
>
> Thomas
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, e-mail: php-general-unsubscribe@lists.php.net
> For additional commands, e-mail: php-general-help@lists.php.net
> To contact the list administrators, e-mail: php-list-admin@lists.php.net
>
>