What are magic methods?

Magic methods are member functions that are available to all the instances of a class.

Magic methods always start with ‘__’, for example, __construct(). All magic methods need to be declared as public.

Example:

__construct()

<?php

class Fruit {

 public $name;

 public $color;


 function __construct($name) {

  $this->name = $name;

 }

 function get_name() {

  return $this->name;

 }

}


$apple = new Fruit("Apple");

echo $apple->get_name();

?>

__destruct()

Ex:

A destructor is called when the object is destructed or the script is stopped or exited.

<?php

class Fruit {

 public $name;

 public $color;


 function __construct($name) {

  $this->name = $name;

 }

 function __destruct() {

  echo "The fruit is {$this->name}.";

 }

}


$apple = new Fruit("Apple");

?>

Sign In or Register to comment.