Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Sharing interfaces using polymorphism

From: Object-Oriented Programming with PHP

Video: Sharing interfaces using polymorphism

When developing an application, I'm typically working with many different kinds of data in different structures, each with a different behavior and need. However, if I were to use different naming conventions for every single data structure, my application would descend into chaos! The phrase "Spaghetti code" is an apt description, meaning the source code is impossibly complex and tangled, like a pile of pasta. Sounds delicious, but it's difficult to organize. To avoid this mess, I can use an object interface. An interface specifies what methods a class must implement, but doesn't say how those methods should be implemented.

Sharing interfaces using polymorphism

When developing an application, I'm typically working with many different kinds of data in different structures, each with a different behavior and need. However, if I were to use different naming conventions for every single data structure, my application would descend into chaos! The phrase "Spaghetti code" is an apt description, meaning the source code is impossibly complex and tangled, like a pile of pasta. Sounds delicious, but it's difficult to organize. To avoid this mess, I can use an object interface. An interface specifies what methods a class must implement, but doesn't say how those methods should be implemented.

There are similarities to an abstract class, but the main importance is that interfaces don't have any methods of their own. In fact, an interface is not a class at all, but it's similar enough that auto loading will work with it. To use an interface, a class uses the keyword implements, followed by the name of the interface. A class can implement more than one interface at a time by separating their names with a comma, as long as those interfaces don't have conflicting method names. Interfaces can also have constants, which will be available to any classes that implement it.

Interface constants cannot be overridden or defined. Overwriting is going to be covered in greater detail in the next segment. So, what's the point of all this? Well, the practice of sharing a common application programming interface, or API, between classes is known as polymorphism. And, interfaces fit that definition quite well, because they're designed exactly for that purpose. In our application, I'm going to define an interface that both the address class and future classes must implement. When designing an interface, try to be as generic as possible, yet still kind of specific enough to be useful.

That sounds like a hard line to walk. So, to demonstrate this, I am going to create a model. A model is responsible for managing data, and storing and retrieving entities, and containing business logic. This aptly describes what the address class is going to be doing at a high level, and applies to future classes as well. I am going to the switch to the IDE. Let's create a new file called Class.Model.Inc. Start with the keyword interface, followed by the name. Shared interface for interactions.

I am going to require two methods in this interface. The first is Load, which will load from the database, given an address ID. I am using Static, as I can't guess what type of address will be returned, so I'll add logic that will return the correct address subclass. The second method will be Save, which will just save to the database. static function load, which takes an address_id. Load a model. param int $address_id. Next, function save, which will save a model. Save, then switch to the Address class.

You want to make the Address class implement the new model interface. So, after the name of the class, add the following: implements Model. If I were to save and refresh the demo, I'd get a fatal error, because the address class doesn't declare the methods from the model interface. We are setting up a situation where there's the possibility that a childs class can potentially declare a method that's already in the parent, like Load or Save. This is known as an override. I don't want to let that happen.

So, I'm going to use the keyword Final. When used on a method, Final prevents childs classes from overwriting the method. So, only the parent address class can describe the save behavior. I can also declare a class as Final, which will keep it from being extended. I'm going to make the Load and Save methods in the address class Final. At the end of the address class, add a final public static function load, which accepts an address_id, placeholder, followed by a final public function save.

Add documentation. param as an integer. And, add documentation. save the address. For now, I'm going to leave the declarations empty, and leave them for a later segment. With the introduction of the final keyword, I mentioned overrides, but didn't go into much detail. In the next segment, I'll discuss how to override methods, properties, and constants.

Show transcript

This video is part of

Image for Object-Oriented Programming with PHP
Object-Oriented Programming with PHP

37 video lessons · 17647 viewers

Jon Peck
Author

 
Expand all | Collapse all
  1. 4m 10s
    1. Welcome
      39s
    2. Exercise files
      2m 16s
    3. What you should know
      1m 15s
  2. 7m 47s
    1. What is an object?
      2m 6s
    2. What is a class?
      2m 7s
    3. Why should you use object-oriented programming?
      2m 14s
    4. The history of object-oriented PHP
      1m 20s
  3. 16m 40s
    1. Defining a class
      2m 58s
    2. Defining class properties
      3m 26s
    3. Creating a method and exploring object context with $this
      2m 50s
    4. Instantiating an object and accessing its contents
      3m 19s
    5. Specifying the visibility scope
      4m 7s
  4. 15m 51s
    1. What is a magic method, and do I need one?
      2m 23s
    2. Overloading property access
      6m 37s
    3. Customizing object construction
      4m 34s
    4. Standardizing object rendering as a string
      2m 17s
  5. 20m 54s
    1. Using the static keyword
      3m 36s
    2. Leveraging scope resolution operators
      1m 10s
    3. Setting constant values
      2m 47s
    4. Implementing static methods
      5m 43s
    5. Creating a database class
      7m 38s
  6. 26m 19s
    1. Extending your class
      6m 8s
    2. Abstracting classes
      5m 57s
    3. Sharing interfaces using polymorphism
      4m 39s
    4. Overriding methods, properties, and constants
      3m 25s
    5. Cloning and comparing objects
      2m 51s
    6. Referencing objects
      3m 19s
  7. 14m 52s
    1. Leveraging standard class objects
      2m 42s
    2. Retrieving objects from the database
      5m 41s
    3. Error handling with exceptions
      2m 6s
    4. Customizing PHP exceptions
      4m 23s
  8. 8m 2s
    1. Identifying the singleton pattern
      1m 42s
    2. Using the factory method pattern
      1m 51s
    3. Implementing a strategy pattern
      4m 29s
  9. 2m 57s
    1. Looking forward to namespaces
      47s
    2. Next steps
      1m 6s
    3. Goodbye
      1m 4s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Object-Oriented Programming with PHP.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

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.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.