Page 1 of 1
[SOLVED] class within a class
Posted: Tue Jun 08, 2004 10:17 pm
by dull1554
if you have a class within a class
i.e.
when i initiate test (new test) does it also initiate test2 or would i have to do a "new test->test2"?
Posted: Tue Jun 08, 2004 10:36 pm
by feyd
dunno offhand.. it wouldn't in C last I used nested classes.. can always try it:
Code: Select all
class test
{
function test()
{
echo "in test()\n";
}
class test2
{
function test2()
{
echo "in test2()\n";
}
}
}
Posted: Tue Jun 08, 2004 10:46 pm
by Weirdan
Are you referring to PHP5?
PHP4 doesn't allow nested classes...
Posted: Tue Jun 08, 2004 10:47 pm
by scorphus
I think you can't do it in PHP 4. I'm not playing with PHP 5 so...
Scorphus
Posted: Tue Jun 08, 2004 11:25 pm
by PrObLeM
Posted: Wed Jun 09, 2004 10:01 am
by dull1554
would that work in php 4?
or if im in php5 do i still need to extend it to the outter class?
Posted: Wed Jun 09, 2004 12:41 pm
by feyd
extends works in 4 and 5
Posted: Wed Jun 09, 2004 2:31 pm
by dull1554
so using extends, it is possiable to nets classes, but if in 5 you car able to do so without extending the class?
do i have it right or is this way over my head?!?!?
Posted: Wed Jun 09, 2004 2:42 pm
by feyd
nested classes, as your original post has them, isn't extending the parent. The nested class is a component of its parent.. like how a function is apart of its parent class.
Posted: Wed Jun 09, 2004 9:40 pm
by dull1554
so it would be more like this.....
Code: Select all
class test{
}
class test2 extends test{
function test3(){echo "test4";}
}
//then
$test = new test;
$test->test2->test3();
after typing this i just tried it and i get an error, what would i have to do to get this to work, i guess im totally missing the point.....
Posted: Wed Jun 09, 2004 10:03 pm
by feyd
Code: Select all
class test
{
function somefunc()
{
echo "joy!";
}
}
class test2 extends test
{
function somefunc()
{
echo "juice!\n";
test::somefunc();
}
}
$blah = new test;
$blah2 = new test2;
or something.. (not tested)
Posted: Wed Jun 09, 2004 10:05 pm
by McGruff
Use inheritance if the two classes are genuinely of the same "type". Suppose you had a Rank class used for adding a ['rank'] key to search results. You might extend this with derived classes which define different types of ranking algorithmns.
It's usually better not to use inheritance if you have another option, ie aggregation or composition.
Code: Select all
<?php
/*
Aggregation:
*/
class Test
{
/*
param (object)
*/
function Test(&$test2)
{
$this->test2 =& $test2;
}
/*
etc..
*/
}
/*
Composition:
*/
class Test
{
function Test()
{
$this->test2 =& new Test2;
}
/*
etc..
*/
}
?>
Incidentally, that last one is known as the Factory pattern - see the design section at
http://www.phppatterns.com.
Posted: Thu Jun 10, 2004 6:00 am
by dull1554
allright, cool, i think i got it now and thanks for all the help