__get & __set in PHP 5

Introduction

Overloading in PHP 5 is a way of dynamically creating properties and methods. To dynamically create properties and methods you have to use magic methods. Magic methods are only used when interacting with properties or methods that have not been declared or are out of scope. PHP is a loosely typed language therefore it is not necessary that you declare variables before using them.

The two magic methods that we are going to look at in this tutorial, __get and __set. __get is used when the you need to read the property of an undefined property of a class and __set is used when you need to set the value of an unassigned variable of a class.

Using __get and __set

Below you can see a class which has the two magic methods and an array. We will use the magic methods to create and read variables from the array:

So using the class above you could create and read data for example:

The code above adds name to the 'info' array. I can now read these values by using the __get method: