PHP magic functions __set() and __get()

PHP Magic FunctionsHere, a simple example of a class declaration in normal way as well as using magic methods. It will clear all your queries regarding the magic functions __set() and __get(). And you would realize, how simple it makes your life!

Since, it is mainly used for property overloading, here is a brief information about overloading in PHP

It basically means creating ‘methods’ and ‘properties’ dynamically in PHP. It is these dynamic entities which are processed via magic methods. The overloading methods are invoked in runtime when interacting with undeclared (or not visible in the current scope) properties or methods. Also, all overloading methods must be defined as public.

Moving on to the example now, We declare a class ‘Car’ with two variables ‘Model Name’ and ‘Color’, in both ways as given under:

In normal classical way

class Car

{

private $model_name = ‘320ld’;

private $color = ‘red’;

public function __construct() {}

 // Setting car’s model name

public function setModelName($model_name)

{

$this->model_name = $model_name;

}

//Setting car’s color

public function setColor($color)

{

$this->color = $color;

}

//To get the car model now

public function getModelName()

{

return $this-> model_name;

}

//Retrieve car’s color

public function getColor()

{

return $this->color;

}

}

In action

We simply create an instance of the class declared above, and assign values to its variables.

$car = new Car();

$car->setModelName(‘576k’);

$car->setColor(‘White’);

Now, to display the results, we use:

echo ‘Car Model Name: ‘ . $car->getModelName() . ‘ and Car color: ‘ . $car->getColor() . ‘ ;

Which will display the following result:

Car Model Name: 576k and Car color: white

 

 Now, using PHP magic functions __set and __get

class Car

{

public function _construct() {}

           // set undeclared property

function __set($property, $value)

{

$this->$property = $value;

}

          // get defined property

function __get($property)

{

if (isset($this->$property))

{

return $this->$property;

}

}

}

In action:

This shows the implementation with property overloading:

$car = new Car();

$car->model_name = ‘576k’;

$car->color = ‘white’;

$car->manufacturer = ‘mercedes’;

Displaying the data i.e. retrieving using get

echo ‘Model Name: ‘ . $car->model_name . ‘,  Color of the Car: ‘ . $car->color . ‘ and Manufacturer: ‘ . $car->manufacturer;

The following result is then displayed:

Model Name: 576k, Color of the Car:  white and Manufacturer: mercedes

This magical property although saves a lot of time, but needs to be used cleverly and carefully. A proper understanding of overloading in PHP is a prerequisite for using these magic methods. For more information on overloading in PHP, jump to this page