Using classes

my problem is how to join 2 classes… i wanted to use the other class inside another class… example

<?
class box {
 
var $arg1;
var $arg2;
 
function box($arg1,$arg2) {
$this->arg1=$arg1;
$this->arg2=$arg2;
}
 
function add() {
return $this->arg1+$this->arg2;
}
}
 
 
class ball {
 
var $arg3;
var $arg4;
 
function ball($arg3,$arg4) {
$this->arg3=$arg3;
$this->arg4=$arg4;
}
 
function multiply() {
return $this->arg3 * $this->arg4;
}
}
?>

now here is the part…

i wanted to have another function inside the class box where i can add and multiply and the multiplication method is by using the class ball… all in all, only 2 classes are used…

tnx… rok on!!!

Hi

I don’t altogether understand your problem.

You can either call the $ball->multiply method or make the ball a member of the box.

class box {
 
var $arg1;
var $arg2;
var $ball;  //a ball object
 
function box($arg1,$arg2,$ball) {
$this->arg1=$arg1;
$this->arg2=$arg2;
$this->ball=$ball;
}

I believe it’s called ‘composition’.

so you would call $box->ball->multiply()
You would have to alter your multiply method so it can accept arguments.

I don’t think PHP allows for the $box->ball->multiply(); syntax. I’ve tried doing it as well and was forced to do


$ball =& $box->ball;
$ball->multiply();

But that’s possibly cause my server isn’t running the most recent PHP version … not sure.

sounds like you may want to extend one of the classes with the other? Making the methods from one avaiable in the other.

It allows me to do it in PHP 4.3.10

Exactly what it sounds like…look on www.php.net for ‘extends.’
From php.net: *Often you need classes with similar variables and functions to another existing class. In fact, it is good practice to define a generic class which can be used in all your projects and adapt this class for the needs of each of your specific projects. *

To use a class ‘inside another class’ you would use composition

My understanding is that to use extends suggests that the extended class is a specialized type of the parent class :-/

Much like the ‘Is A’ vs ‘Has A’ argument in Colin Moock’s Actionscript 2.0 book.

To extend it you’d make a generic ‘shape’ class which had a multiply method and then extend both the box and the ball from that class.

Which has it’s benefits.

:beam:

Sounds like either might work:

For Composition See:
http://www.devshed.com/c/a/PHP/Object-Interaction-in-PHP-Introduction-to-Composition-conclusion/

For Extends See:
http://us2.php.net/manual/en/language.oop5.basic.php