Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
Instead of just asking an object to display itself, it's more convenient to assume that when echoed, an object knows to treat itself like a string. At a high level, this concept is known as polymorphism, where I can act on an object without knowing exactly what the class is. In practice, this means more common function names between classes. I am going to cover polymorphism in greater depth in a later segment. For now, let's focus on making an address display as a string by echoing. To do this, I'm going to use the magic method _toString(), which allows an object to specify how to return a string.
I am going to switch back to the demo script. Then, at the end, add the following
Address _toString. Then echo $address_2. Refresh your browser.
You will see a catchable fatal error.
This is because the object does not have a method defined to convert itself to a string.
Open the Address class. Under the Magic _set() method, declare a new method
called _toString. Add the PHP documentation. Magic _toString returns a string
As you already defined the method to display the address, call it from
_toString, and return its value. return this->display. Save, then return to
your browser, and refresh.
Instead of an error, you will see the address rendered as if you called the display method directly. This is just one example of polymorphism, and I'll get into sharing interfaces a bit later. In this chapter, I've been focusing on overloading with magic methods. I started by defining just what magic methods are, then demonstrated them by overloading property access and by restricting visibility. I customized object construction by setting the time that the object was created automatically, then made an address treat itself like a string, using polymorphism.
So far, we've worked with classes and instances, but did you know that you can access methods and properties without instantiating an object?
Get unlimited access to all courses for just $25/month.Become a member
61 Video lessons · 99946 Viewers
56 Video lessons · 113035 Viewers
71 Video lessons · 81881 Viewers
131 Video lessons · 39290 Viewers
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.