Lesson 15

Using Advanced Techniques

Now that you have a grasp of the basic concepts of using classes and objects in PHP, you are ready to learn more advanced techniques. In this lesson you learn easier ways of including the code for the class files and best practice techniques for updating and accessing properties. You learn how to use scope with classes to make your code more secure.

You also learn how to extend classes so that you can build on stable classes, and how to organize the functionality in your program by using static functions and classes.

Initializing the Class

Best practice dictates that you create a new file for each of your classes. You also have to include any of those files once, and only once, to define the class before you can use it. You can use different techniques to do this.

As you learned in the previous chapter, you can use require_once statements at the beginning of your program or just before you use your classes. This, however, can result in a lot of tedious code or a lot of extra code that might never be needed.

PHP has what are called “magic methods.” These are functions that are called automatically at certain times. One magic method you are familiar with is _contruct(), which is called when you create a new object. Magic methods start with a double underscore.

PHP has a magic function called _autoload() that is automatically called if you try to use a class that has not been defined. You define this function at the beginning of your program and ...

Get PHP and MySQL® 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.