PHP __get And __set Magic Methods

PHP is a loosely typed programming language, one of the features of a loosely typed language is that you can use variables without declaring them or their type.

In other languages such as c# you need to declare the variable when you use it and the type of variable.

Below is an example of declaring a variable in c# and then PHP.

// c# code to declare a variable
string var = "Declaring a variable var";

and in PHP

// php code to declare a variable
$var = "Declaring a variable var";

This is also true in class members.

class newClass {

public $name;

}

$c = new newClass();

$c->name = "Person Name";
$c->email = "email@address.com";

In other languages like c# this will generate an error but it works perfectly fine in PHP. Because of this feature in PHP they give you two magic methods __get() and __set().

The purpose of these methods will be to run when you try to access a variable which has not been declared. For example if you try to set a variable like in the above example PHP will run the __set() method or when it tries to get a variable that is not set it will run the __get() method. In here you are able to do what ever you want to handle the variable, you can accept the loosely typed functionality or make it so you need to declare variables by throwing an exception in these method.

class newClass {

public $name;

public __set($name, $value){
     throw new Exception("Variable ".$name." has not been set.", 1);
}

public __get($name){
     throw new Exception("Variable ".$name." has not been declared and can not be get.", 1);
}

}

$c = new newClass();

$c->name = "Person Name";
$c->email = "email@address.com";

Advertise here 50% Off

Comment