Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
Another structural feature of classes are methods. A method is pretty much a function within a class. Methods follow the same naming conventions as regular functions, which are the same as the rest of the PHP labels. Best practice dictates a similar naming convention to properties with lowerCamel case naming. The first method we're going to build meets a common need, displaying an address with HTML formatting. The end result will look something like 555 Fake Street, Townsville, State 12345, United States of America.
To keep us focused, I'm not going to include any type of data sanitizing when rendering the data. To make this production-ready, you should use something like htmlspecialchars, as users should never be trusted. In the ID, let's start with a sub declaration for the display method. function display. output is empty. return output. Let's add proper documentation. Display an address in HTML.
In order to display the contents of an address, I need to be able to access the properties of the object. If I'm using a method within the object, I can use the pseudo variable "$this." $this is a reference to the calling object, which is almost always the object that the method belongs to. To access properties of an object using $this, append "->" to $this, followed by the name of the property without a dollar sign. For example, if I have an address instance with a property named "city" and a value of "San Diego," a method that accesses this city will be able to get the contents of the city property, which is San Diego.
Back to the display function. We'll start with a street address. $output = $this->street_ address_1. And, then some logic. If there is a street_address_ 2, display it on a new line. Next, we'll have the City, Subdivision, and the Postal Code. Output, new line, output the city name followed by a comma, then subdivision name, space, and the postal code. Finally, the country, new line, and then the country name.
Now that the method definition is complete, I'll save the file. In the next movie, we'll take a look at instantiating an object, and accessing its contents.
Get unlimited access to all courses for just $25/month.Become a member
82 Video lessons · 97456 Viewers
61 Video lessons · 84687 Viewers
71 Video lessons · 68887 Viewers
56 Video lessons · 101331 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.
Your file was successfully uploaded.