06.
Objects Interact
Keep on Learning!
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
Whoops, an error! Please, try again later.
4 Comments
Loving the courses! Question. How do I know $this refers to $myShip and not $otherShip?In a previous video it was stated that "$this is whatever Ship object that we are calling the method on". Now that we have two objects in play here I'm not confident I understand.
Hey Brittany J.
It's pretty simple.
$thisis some sort of magic variable, for example, if you call$myShip->doesGivenShipHaveMoreStrength()than insidedoesGivenShipHaveMoreStrength(),$thiswill be$myShipobject, but if you call$otherShip->doesGivenShipHaveMoreStrength()than it will be$otherShip.So
$thisvariable inside Class is always refers to the object from which the method was called.Cheers! Hope it's more clear now.
I am not clear about this line,
will you give a explanation how this line working here?
Hey Md mamunur R.!
GREAT question! Let me rewrite this function so that it does the SAME thing, but is a little bit more clear:
If you look at this function, I hope it's more clear. If the $givenShip strength is greater than (>) THIS ship's strength, then the method returns true. Else, it returns false.
This code does the exact same thing as my original code:
In this line, PHP first determines the value of
$givenShip->strength > $this->strength, which will betrueorfalse. Then, it returns that value (it returns true or false).If this "shorter" way of writing the method looks confusing to you, then you should feel comfortable writing it the longer, more clear way. Code readability is really important - you certainly don't always need to do things the "shortest" way.
Cheers!
"Houston: no signs of life"
Start the conversation!