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

Extending your class

From: Object-Oriented Programming with PHP

Video: Extending your class

In this chapter, I'm going to introduce class hierarchies. First, I'm going to demonstrate how classes can relate to one another. Then I'll show how to create blueprints for classes and methods. We'll make unified interfaces with polymorphic behaviors. I'll demonstrate how to override methods, properties, and even constants. We'll copy and compare objects, then finally explore ways that objects can be manipulated indirectly. Before we go any further, I'd like to teach you a neat way of dealing with large numbers of class files gracefully.

Extending your class

In this chapter, I'm going to introduce class hierarchies. First, I'm going to demonstrate how classes can relate to one another. Then I'll show how to create blueprints for classes and methods. We'll make unified interfaces with polymorphic behaviors. I'll demonstrate how to override methods, properties, and even constants. We'll copy and compare objects, then finally explore ways that objects can be manipulated indirectly. Before we go any further, I'd like to teach you a neat way of dealing with large numbers of class files gracefully.

Currently in the demo file, we're explicitly requiring both the address and the database class. However, as we add more classes with one file per class, things are going to get a bit messy with more requires. Good thing there is another option. As of PHP 5, a new solution was added, known as Autoloading classes. If you define an autoload function, it will automatically be called whenever you try to access a class that hasn't been defined yet, kind of like a failsafe before PHP gives up, and has a fatal error.

I am going to replace the two require statements at the top of the demo with an autoload function definition. function __autoload, which takes one argument. $class_name. include anything that starts with 'class.' and then the class_name.inc. Define autoloader with one parameter string $class_name. Save the file.

Now that we future-proofed the application, let's discuss inheritance. Inheritance is a core object-oriented principle, where relationship between classes can be established. Think of it as a parent and child relationship, where the parent is a class, and a child is a subclass of the parent. The child inherits all of the parent's behaviors and properties, making it an inclusive superset of both the child and the parent. There are a number of characteristics of inheritance that are useful. Both the parent and the child share common functionality, without having to copy and paste code.

The child can have new functionality that the parent does not. Therefore, the child extends the parent, which is also the key word used. The only way that a child can extend a parent is if the parent has been declared. Classes can extend only one class's methods and properties at a time. You can't specify multiple classes to extend. You can, on the other hand, extend a class that extends another class. You just can't extend two classes simultaneously. This is a lot to think about, so let's see it in action.

In the previous chapter, we added a property to the address class to track what type of an address an object was: a residence, business, or park. I want to avoid code duplication, but still be able to add address type specific behavior. Therefore, I'll make address a parent class, and make child classes for the three address types. We'll implement unique behaviors in the next segment. I'm going to switch back to the IDE. In the previous chapter, you added a property to the Address class to track what type of an address an object was: a residence, business or park.

For this exercise, I'm going to assign a different behavior to each address type. You'll implement that behavior in the next video, but to do so, you'll need a place to put it. Start the class definition with the name of the class, followed by the keyword extends, then the name of the class you are extending. PHP label conventions apply to the name of the class, but best practice is to start with the name of the class you are extending. Create a new file in your Exercise folder called class.AddressResidence.inc.

Start the class definition with the name of the class, followed by the keyword extends, then the name of the class you're extending. PHP label conventions apply to the name of the class, but the best practice is to start with the name of the class you're extending. class AddressResidence extends Address. Add quick documentation, and save. That's all that needs to be added for now as different behavior will be defined later.

Next, create a new file for the business address called class.AddressBusiness. The contents will be virtually identical. Save, then create the final file for a park address. class.AddressPark.inc.

And then, class.AddressPark extends Address. Save, and return to the demo file. Following the autoloader, change the title to AddressResidence. Address is new AddressResidence. And, re-factor the remaining code. Add debugging to display the contents of the address_residence variable. echo

 var_export{$address_ residence, TRUE} close pre, close tt.
						
					

Save, then switch to your browser. When you refresh the page, you will see that the class is now address_residence, and that all the functionality that you previously defined in the Address class still works, and is still accessed in the same manner. Also note that the second address, which is just class address, functions as it was before, even as a parent. In the next video, I'll demonstrate how to prevent the use of the parent address, and how to add custom behaviors to the child classes.

Show transcript

This video is part of

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

37 video lessons · 19127 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

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 preferences from 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.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your lynda.com subscription:
  •   Download videos to your device
  •   Access course practice files
  •   Get 12 months for the price of 10

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

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:

  • new course releases
  • newsletter
  • general communications
  • special notices

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:

  • new course releases
  • newsletter
  • general communications
  • special notices

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.