22
Jul
Some useful Magic methods of php
- Category:
- Methods of PHP
- PHP
Posted On : July 22, 2013
| No Comment
The “magic” methods are ones with special names, starting with two underscores(__)
They are functions that are always defined inside classes, and are not stand-alone (outside of classes) functions.
The magic functions available in PHP are below:
- __construct()
- __destruct()
- __call()
- __callStatic()
- __get()
- __set()
- __isset()
- __unset()
- __sleep()
- __wakeup()
- __toString()
- __set_state()
- __invoke()
- __clone()
Example of magic methods
1) __construct()
The most commonly used magic function is __construct().
Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.
Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <!--?php class ParentClass { function __construct() { print "Call ParentClass constructor\n"; } } class ChildClass extends ParentClass { function __construct() { parent::__construct(); print "Call ChildClass constructor\n"; } } $obj = new BaseClass(); // Output:- Call ParentClass constructor $obj = new SubClass(); /* * Output:- Call ParentClass constructor Call ChildClass constructor * */ $obj = new OtherSubClass(); // Output:- Call ParentClass constructor ?--> |
2) __destruct()
It gets run when the object is destroyed
Like constructors, parent destructors will not be called implicitly if the child class defines a constructor. In order to run a parent destructor, one would have to explicitly call parent::__destruct() in the destructor body.
1 2 3 4 5 6 7 8 9 10 11 12 | <!--?php class ExampleDestruct { function __construct() { print "In constructor\n"; $this--->name = "ExampleDestruct"; } function __destruct() { print "Destroying " . $this->name . "\n"; } } $obj = new MyDestructableClass(); ?> |
3) __get(),__set(),__isset() and __unset()
__set() is run when writing data to inaccessible properties.
__get() is utilized for reading data from inaccessible properties.
__isset() is triggered by calling isset() or empty() on inaccessible properties.
__unset() is invoked when unset() is used on inaccessible properties.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | <!--?php class ExampleSetMethod { protected $_values = array("cget" =--> "call __get method"); public function __get($key) { return $this->_values[$key]; } public function __set($key, $value) { $this->$key = $value; } public function __isset($name) { echo "Is '$name' set?"; return isset($this->_values[$name]); } public function __unset($name) { echo "Unsetting '$name'"; unset($this->_values[$name]); } } $obj = new ExampleSetMethod(); // __set() will be called here $obj->setvariable = 'something'; echo $obj->setvariable; // Not call __set() because 'setvariable' is now declared $obj->setvariable = 'other thing'; echo ""; print $obj->cget; echo ""; var_dump(isset($obj->a)); echo ""; unset($obj->a); var_dump(isset($obj->a)); /* Output:- something call __get method Is 'a' set? bool(false) Unsetting 'a' Is 'a' set? bool(false) */ ?> |
4) __call() and __callStatic()
‘Call’ is triggered when invoking inaccessible methods in an object context. For methods in a static context you should use ‘callStatic’.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <!--?php class ExampleCall { public function __call($name, $arguments) { echo "Call method '$name' " . implode(', ', $arguments) . ""; } public static function __callStatic($name, $arguments) { echo "Call static method '$name' " . implode(', ', $arguments) . "\n"; } } $obj = new ExampleCall(); $obj--->runCall('in object context'); ExampleCall::runCall('in static context'); /* output:- Call method 'runCall' in object context Call static method 'runCall' in static context */ ?> |
5) __toString()
The __toString() method allows a class to decide how it will react when it is treated like a string.
For example, what echo $obj; will print. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR level error is emitted.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <!--?php class ExampleToString { public $foo; public function __construct($foo) { $this--->foo = $foo; } public function __toString() { return $this->foo; } } $class = new ExampleToString('Hello'); echo $class; /* output:- Hello */ ?> |
6) __sleep() and __wakeup()
The intended use of __sleep is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which need not be saved completely.
The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | <!--?php class ExampleSleepAndWackup { private $name = ''; private $address = 0; private $dob = array(); public function __construct($name, $address, $dob) { $this--->name = $name; $this->address = $address; $this->dob = $dob; } public function show() { echo $this->name; } function __sleep() { echo 'Going to sleep...'; return array('name', 'address', 'dob'); } function __wakeup() { echo 'Waking up...'; } } $obj = new ExampleSleepAndWackup('test', 'testcity', "1999-09-09"); $obj->show(); echo "\n"; $s = serialize($obj); echo $s . "\n"; $fp = fopen('session.s', 'w'); fwrite($fp, $s); fclose($fp); $s = implode('', file("session.s")); echo $s . "\n"; $a = unserialize($s); $a->show(); /* Output :- test Going to sleep... O:21:"ExampleSleepAndWackup":3:{s:27:"ExampleSleepAndWackupname";s:4:"test";s:30:"ExampleSleepAndWackupaddress";s:8:"testcity";s:26:"ExampleSleepAndWackupdob";s:10:"1999-09-09";} O:21:"ExampleSleepAndWackup":3:{s:27:"ExampleSleepAndWackupname";s:4:"test";s:30:"ExampleSleepAndWackupaddress";s:8:"testcity";s:26:"ExampleSleepAndWackupdob";s:10:"1999-09-09";} Waking up... test */ ?> |
7) __invoke()
The __invoke() method is called when a script tries to call an object as a function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!--?php class ExampleInvoke { public function __invoke($x) { var_dump($x); } } $obj = new ExampleInvoke; $obj("call invoke method"); /* * Output:- string(18) "call invoke method" */ ?--> |
__set_state()
This static method is called for classes exported by var_export().
The only parameter of this method is an array containing exported properties in the form array(‘property’ => value, …)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <!--?php class ExampleState { public $var1; public $var2; public static function __set_state($an_array) { // As of PHP 5.1.0 $obj = new ExampleState; $obj--->var1 = $an_array['var1']; $obj->var2 = $an_array['var2']; return $obj; } } $a = new ExampleState; $a->var1 = 5; $a->var2 = 'string'; eval('$b = ' . var_export($a, true) . ';'); var_dump($b); /* * Output:- * object(ExampleState)#2 (2) { ["var1"]=> int(5) ["var2"]=> string(6) "string" } */ ?> |
9) __clone
An object copy is created by using the clone keyword (which calls the object’s __clone() method if possible). An object’s __clone() method cannot be called directly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | <!--?php class SubObject { static $instances = 0; public $instance; public function __construct() { $this--->instance = ++self::$instances; } public function __clone() { $this->instance = ++self::$instances; } } class MyCloneable { public $object1; public $object2; function __clone() { // Force a copy of this->object, otherwise // it will point to same object. $this->object1 = clone $this->object1; } } $obj = new MyCloneable(); $obj->object1 = new SubObject(); $obj->object2 = new SubObject(); $obj2 = clone $obj; print("Original Object:\n"); print_r($obj); print("Cloned Object:\n"); print_r($obj2); /* * Output Original Object: MyCloneable Object ( [object1] => SubObject Object ( [instance] => 1 ) [object2] => SubObject Object ( [instance] => 2 ) ) Cloned Object: MyCloneable Object ( [object1] => SubObject Object ( [instance] => 3 ) [object2] => SubObject Object ( [instance] => 2 ) ) */ ?> |
I hope this can be useful to other PHP developers just starting the world of OOP.