Login to bookmark this video
Buy Access to Course
06.

Objects Interact

Share this awesome video!

|

Keep on Learning!

Since the goal of our app is to let two ships fight each other, things are getting interesting. For example, we could fight $myShip against $otherShip and see who comes out as the winner.

But first, let's imagine we want to know whose strength is higher. Of course, we could just write an if statement down here and manually check $myShip's strength against $otherShip.

But we could also add a new method inside of the Ship class itself. Let's create a new method that'll tell us if one Ship's strength is greater than another's. We'll call it: doesGivenShipHaveMoreStrength(). And of course, it needs a Ship object as an argument:

86 lines | play.php
// ... lines 1 - 2
class Ship
{
// ... lines 5 - 43
public function doesGivenShipHaveMoreStrength($givenShip)
{
// ... line 46
}
}
// ... lines 50 - 86

So just like with our printShipSummary() function, when we call this function, we'll pass it a Ship object. What I want to do is compare the Ship object being passed to whatever Ship object we're calling this method on. Before I fill in the guts, I'll show you how we'll use it: if $myShip->doesGivenShipHaveMoreStrength() and pass it $otherShip. This will tell us if $otherShip has more strength than $myShip or not. If it does, we'll echo $otherShip->name has more strength. Else, we'll print the same thing, but say $myShip has more strength.

86 lines | play.php
// ... lines 1 - 78
echo '<hr/>';
if ($myShip->doesGivenShipHaveMoreStrength($otherShip)) {
echo $otherShip->name.' has more strength';
} else {
echo $myShip->name.' has more strength';
}

Inside of the doesGivenShipHaveMoreStrength(), the magic $this will refer to the $myShip object, the one whose name is Jedi Starship. So all we need to do is return $givenShip->strength greater than my strength:

86 lines | play.php
// ... lines 1 - 2
class Ship
{
// ... lines 5 - 43
public function doesGivenShipHaveMoreStrength($givenShip)
{
return $givenShip->strength > $this->strength;
}
}
// ... lines 50 - 86

Ok, let's try it! When we refresh, we see that the Imperial Shuttle has more strength. And that makes sense: the Imperial Shuttle has 50 compared with 0 for $myShip, because it's using the default value.

Let me add another separator and let's double-check to see if this is working by setting the strength of $myShip to 100.

Ok, refresh now! Now the Jedi Starship is stronger. Undo that last change.

So how cool is this? Not only can we have multiple objects, but they can interact with each other through methods like this one. I'll show you more of this later.