PHP OOP magic methods

PHP magic methods call automatically on certain type of events or actions.

List of magic methods

  1. __construct
  2. __destruct
  3. spl_autoload_register
  4. __get
  5. __set
  6. __call
  7. __callStatic
  8. __isset
  9. __unset
  10. __toString
  11. __sleep
  12. __wakeup

__construct

Call automatically when the object of class created.

Example

class Home{
	public function __construct(){
		echo "starting...";
	}
}

$h=new Home();

__destruct

Call automatically when the functionality of the class completed.

class Home{
	public function __construct(){
		echo "starting...";
	}
	public function __destruct(){
		echo "ending...";
	}
	public function first(){
		echo "first method <br>";
	}
	public function second(){
		echo "second method <br>";
	}
}

$h=new Home();
$h->first();
$h->second();

spl_autoload_register

This method call automatically when object of class created.

spl_autoload_register(function($class){	
	$class = str_replace("\\", DIRECTORY_SEPARATOR, $class);
	$path=	$class.".php";	
	require_once $path; 
});
$first = new First\FirstClass();
echo $first->name;

__get()

This method call automatically when properties of class is accessing.

class Account{
	public $name;
	public function __construct($name){
		$this->name = $name;
	}
	public function __get($property){
		echo "This $property does not exist";
	}
}

$acc= new Account("Aman");
echo $acc->age;

__set()

This method calls automatically when properties of a class change or set a new value.

class Account{
	public $name;
	public function __construct($name){
		$this->name = $name;
	}
	public function __get($property){
		echo "This $property does not exist";
	}
	public function __set($property, $value){
		echo "This $property does not exist";
	}
}

$acc= new Account("Aman");
$acc->age = 32;

__call()

This method calls automatically when accessing member method of class using object.

class Account{
	private $name;	
	private function setData($name){
		$this->name = $name;
	} 

	public function __call($method, $args){
		if(method_exists($this, $method)){
			call_user_func_array([$this, $method], $args);
		}
		else{
			echo "This method does not exists.";		
		}
	}

}

$acc= new Account();
$acc->setData("Aman");

echo "<pre>";
print_r($acc);
echo "</pre>";
© 2016 - 2022, All Rights are Reserved.