Start your free trial now, and begin learning software, business and creative skills—anytime, anywhere—with video instruction from recognized industry experts.

Start Your Free Trial Now

Overloading property access

Overloading property access provides you with in-depth training on Developer. Taught by Jon Peck as … Show More

Object-Oriented Programming with PHP

with Jon Peck

Video: Overloading property access

Overloading property access provides you with in-depth training on Developer. Taught by Jon Peck as part of the Object-Oriented Programming with PHP
Expand all | Collapse all
  1. 4m 10s
    1. Welcome
    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 17s
    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 17s
  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
    2. Next steps
      1m 6s
    3. Goodbye
      1m 4s

please wait ...
Overloading property access
Video Duration: 6m 37s 1h 57m Intermediate Updated Apr 10, 2013


Overloading property access provides you with in-depth training on Developer. Taught by Jon Peck as part of the Object-Oriented Programming with PHP

View Course Description

Whether you're enhancing or optimizing existing code or just starting from scratch, there's never a better time to start integrating object-oriented design techniques. This course shows how to integrate the principles of object-oriented programming into the build of a PHP-driven web page or application. After an overview of what objects and classes are and why they should be used, author Jon Peck dives into creating and instantiating objects, then defining the class relationships and interactions that will form the basis of your coding arsenal. The course also shows how to leverage PHP objects and implement design patterns, and looks at steps you can take to continue adding to your programming tool belt.

Topics include:
  • Historical overview of object-oriented PHP
  • Defining classes
  • Creating a method/object context with $this
  • Accessing classes without instantiation
  • Creating a database class
  • Extending and abstracting classes
  • Cloning and comparing objects
  • Error handling with exceptions
  • Implementing design patterns, such as the factory and strategy patterns

Overloading property access

Within PHP, overloading means to dynamically create a property or method that has not been declared, or is not visible in the current scope. When I say create, it's figurative. PHP will act like they exist and can be accessed, even though in reality they don't. These dynamic entities are processed using magic methods. Object properties have two events that can be invoked when accessing a missing or out-of-scope property: when a script _gets a property, and when a script _sets a property. They can be useful to do things like use a method or function to determine the value to be returned, or execute some sort of failsafe behavior when trying to set a property that doesn't exist.

Both the get and the set magic methods have public visibility, so you don't have to specify scope when declaring them. In the Address class, a magic _get method would be useful for calculating a missing postal code. For example, if the postal code was null, but there is a city in subdivision, I could attempt to look up the value in a table. However, as the postal code is currently public, the magic _get method won't be triggered. Therefore, we'll change the scope of the postal code to protected, in order to be able to use the magic _get.

I'll demo the database lookup later. For the time being, we'll put in a placeholder and focus on magic methods. Open the Address class, then change the scope of postal code to protected. Remember to prepend the property name with an underscore (_) to visually indicate the scope. Then start editing the file after the last property declaration. Add a placeholder function for the database lookup for the postal code. As there is no need to expose this function outside of the address class, protected as well. protected function _ postal_code_guess, return LOOKUP. Add proper PHP documentation, guess the postal code given the subdivision and city name, to do.

Replace with a database LOOKUP. Now that you have a postal code placeholder, you can now leverage the magic _get method. They take only one argument, the name of the property in the form of a string. Place the Magic _get method above the protected method, postal_code_guess. function__get name. Then, documentation Magic _ get. Name as a string, and returns next.

Insert the logic for the special behavior for the postal code property. Postal code lookup if I set, if no postal_code, and set postal code to _postal_code_guess. After the special condition for postal code, you'll expose any protected properties that start with an underscore as read-only. Remember, this will get around scope restrictions.

So, only do this if you are aware of the potential consequences, such as accidentally exposing internal data. In this case, there is no harm in exposing all protected properties as read-only. Attempt to return a protected property by name. You cannot call a property using a concatenated string, so create a variable that starts with the underscore followed by the name. $protected_property_name=_ followed by $name. if property_exists in this with the property name, return this protected_property_name.

If the property does not exist, trigger a PHP error and return null. trigger_error Undefined property via _ get, followed by the name. return NULL. If you were to test the script now, you would get a failure when you attempted to set the postal code, as it is currently protected. Therefore, you will also need to define a magic _set to handle that circumstance.

Beneath the magic _get, define a magic _set method. The magic _set method has two arguments. The first is the name of the property as a string, and the second is a mixed value to be set. function__set name, value. Add the PHP documentation, string for name, mixed for value. Add the check for the postal code property, and allow anything to manipulate it. In this example, stick with a simple if statement, as there is only one logical check.

If there were multiple property names that you are checking for, a switch statement may be more readable. Allow anything to set the postal code. If postal code is the name, this name = value. return. If the property is not postal code, trigger contextually appropriate error. Unable to access property; trigger error. trigger_error ('Undefined or unallowed property via _ _set (); followed by the name); Save the address class, then open the demo file. At the end, remove the unintentional failed display of address ID. Then, let's test the new magic _get method by unsetting the postal code, and displaying the result.


Testing magic _get and _ set; unset ($address postal_code); echo $address_display();. Save the demo file, then refresh your browser. The first instance of the postal code shows up as expected, and the second instance with no postal code now shows the word LOOKUP. In the next video, you can set the time created, leveraging a construction magic method.

Find answers to the most frequently asked questions about Object-Oriented Programming with PHP .

Expand all | Collapse all
please wait ...
Q: I'm not seeing warnings or errors in my environment like the video; why not?
A: Your PHP configuration is probably configured not to show them to you. This is often true on commercial web hosts and is often the default. Fortunately, there are multiple ways of resolving this.

The easiest way would be to explicitly enable error reporting at the top of the PHP script you wish to debug.

error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);

Alternatively, if you have access to your php.ini file and you want to always have error reporting on, change error_reporting = to a development friendly value of

error_reporting = E_ALL | E_STRICT

then change display_errors = to

display_errors = On

Finally, if access to the php.ini file is not available, you can add the following directives to your .htaccess or VirtualHost configuration for Apache:

php_value error_reporting 32767
php_value display_errors 1

If you would like a development optimized development environment like the one utilized in this course, see Up and Running with Linux for PHP Developers, here in the online training library.

Q: This course was updated on 4/10/2013. What changed?

A: The author rerecorded some of the tutorials to add more background information and better graphics.






Don't show this message again
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.

* Estimated file size

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


You have completed Object-Oriented Programming with PHP.

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


Upgrade to View Courses Offline


With our new Desktop App, Annual Premium Members can download courses for Internet-free viewing.

Upgrade Now

After upgrading, download Desktop App Here.

Become a Member and Create Custom Playlists

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

Get started

Already a member?

Log in

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:

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.

You started this assessment previously and didn’t complete it.

You can pick up where you left off, or start over.

Resume Start over

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 subscription:

“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 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

Sign up and receive emails about 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.