6.4. Constructors and Destructors

If you choose to declare a function within a class named __construct, the function will be considered a constructor and will be executed immediately upon creating an object from that class. To be clear, the first two characters are underscores. Like any other function, the constructor may have parameters and even default values. You can set up classes that allow you to create an object and set all its properties in one statement. You may also define a method named __destruct. PHP calls this method when it destroys the object. It's called a destructor.

One powerful aspect of classes is inheritance, the idea that a class can extend the functionality of another class. The new class will contain all the methods and ...

Get Core PHP Programming, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.