PHP

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 function __set($name, $value){
        throw new Exception("Variable ".$name." has not been set.", 1);
    }

    public function __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";
Back to top ^

Join Paulund

  • Get access to 100s of premium tutorials and downloadable content
  • Members content consists of Premium WordPress plugins, CSS packages, jQuery packages, tutorial demo files and templates for 100s of web development tutorials
  • In-depth development tutorials
  • Priority tutorial requests
  • Priority email development support
  • No ads

Here at Paulund you'll find Web Development tutorials and snippets focusing mainly on PHP, WordPress and CSS. Members will get access to premium tutorials that go into more detail about development with these languages. You will also get access to downloadable premium content based on the tutorial.

Join Paulund

Leave a Reply

Your email address will not be published. Required fields are marked *