PHP provides built-in interceptor methods (also called magic methods), which are automatically executed in some special cases, when are accessed undefined methods and properties.
- Magic methods must be defined with "public" attribute.

__get() and __set() methods

The __get() and __set() methods are generally used together and are designed for working with properties that are not defined in a class (or its parents). The __get() method must be defned with one parameter and the __set() must be declared with two arguments.

  - Example:
In the following example we create a class, named AClas, with __get() and set() methods. then we create an object instance of this class.
// AClas
class AClas {
  // define a property which will store the values assigned to undefined properties
  public $prop = array();

  // __get() interceptor method
  public function __get($name) {
    // if there is an element '$name' in $prop array, outputs its value
    // else, display a message
    if(array_key_exists($name, $this->prop)) echo $this->prop[$name]. '<br />';
    else echo 'The <b>'. $name. '</b> not defined.<br />';

  // __set() interceptor method
  public function __set($name, $value) {
    // add in $prop array an element with $name as key, and $value. Then outputs a message
    $this->prop[$name] = $value;
    echo 'The <b>'. $name. '</b> not exists. It was assigned the value: <i>'. $value. "</i> to the property: <b>prop['$name']</b><br />";

// object instance of the AClas class
$obj = new AClas();

// access an undefined property
$obj->noprop;            // It will cause the execution of the __get() method

// assign a value to a undefined property
$obj->noprop = 'noprop - PHP OOP';           // will cause the execution of the __set()

// access again the same undefined property
$obj->noprop;           // the __get() is automatically invoked

// checking directly the element which __set() created it in $prop
echo 'Verificare: '. $obj->prop['noprop'];
The $prop property is defined as array to store the values of undefined properties, which are intercepted by the __set() method.
Becouse the $noprop doesn't exist in this class, accessing $obj->noprop; causes the execution of the __get() method, which gets the name of that property.
Assigning a value to "noprop" causes the execution of the __set() method, which gets the name of the property and its values and uses them to create an array element in $prop.
Se also the comments in script.
This example will output:
The noprop not defined.
The noprop not exists. It was assigned the value: noprop - PHP OOP to the property: prop['noprop']
noprop - PHP OOP
Verificare: noprop - PHP OOP

The __call() method

The __call() method is invoked when an undefined method is called. It must be defined with the following sintax:
  - Syntax:
public function __call($method, $arg_array)
$method will contain the name of the undefined method.
$arg_array is an array with the arguments passed to that undeclared method

  - Example:
In this example we create a class, named AClass, with a __call() method wihch returns a string with the name of the undefined method that is called, and all arguments passed.
// AClas class
class AClas {
  // __call() method
 public function __call($name, $args) {
    // displays a string withe the undeclared method ant its arguments
    echo 'There is no <b>'. $name. '</b> method. Arguments: <i>'. implode(', ', $args). '</i>';

// object instance of the AClas class
$obj = new AClas();

// calling an undefined method
$obj->site('coursesweb', 'tutorials');           // will automatically invoke the __call() method
This code will output:
There is no site method. Arguments: coursesweb, tutorials

toString() method

The toString() method is invoked automatically when the object instance is passed to print or echo.
  - Example:
In the following example is created a class with __construct(), a property ($msg) and a __toString() method which will return the value of $msg property.
// AClas class
class AClas {
  private $msg;       // Proprietate

  // Constructor
  public function __construct($msg) {
    // sets the value of "msg" property with the $msg attribute
    $this->msg = $msg;

  // __toString() method
  public function __toString() {
    return $this->msg;        // return the $msg property

// object instance of the AClas class
$obj = new AClas('Have a good life');

// prints the object instance as a normal variable string type
echo $obj;           // will cause the auto-calling of __toString()
echo $obj; outputs what the __toString() returns.
This example will display:
Have a good life
Without the __toString() declared in AClass, trying to print the object instance ($obj) as a string will generate an error like this:
Catchable fatal error: Object of class AClas could not be converted to string in ...

• There are other magical methods too, less used. You can find full list at the page: Magic methods.

Daily Test with Code Example

Click on the HTML tag which creates an horizontal line in web page.
<br /> <em> <hr />
Some content ...
<hr />
Content under line ...
Which CSS property defines the text color?
font-style font-variant color
h2 {
  color: #cbdafb;
Click on the function which searches if a character, or text exists in a string.
indexOf() toString() split()
var str = "Web courses -";
if(str.indexOf("http://") == -1) alert("http:// isn`t in string");
else alert("http:// is in string");
Which function splits a string into an array of strings based on a separator?
array_merge() explode() implode()
$str = "apple,banana,melon,pear";
$arr = explode(",", $str);
var_export($arr);      // array (0=>"apple", 1=>"banana", 2=>"melon", 3=>"pear")
Magic Methods __get, __set, __call, __toString

Last accessed pages

  1. Get search data from URL address in JavaScript (2488)
  2. PHP OOP - Final Classes and Methods (4295)
  3. CSS Course - Free lessons (9653)
  4. Fotorama Image Gallery (3828)
  5. jqPlot Charts (5235)

Popular pages this month

  1. Making DIV Contents Scroll Horizontally, with multiple Div`s inside (1082)
  2. Contact page - CoursesWeb (1054)
  3. Tabs effect with CSS (1050)
  4. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (453)
  5. PHP getElementById and getElementsByTagName (332)