Magic Functions in PHP – Quick Tips

Author: | Posted in PHP, Quick Tips No comments

Magic Functions in PHP

  1. All function starts with double underscore(__)
  2. PHP reserves all function names starting with __
  3. It allows to define class functionality without needing to duplicate code.
  4. It can be defined inside the class only.
  5. It can be triggered at any point of code(event).
  6. Magic functions will never directly be called by the programmer – actually, PHP will call the function ‘behind the scenes’. This is why they are called ‘magic’ functions – because they are never directly called, and they allow the programmer to do some pretty powerful things

Example:

  1. __construct(): It called at creation of objects.
  2. __destruct() : it called when all reference of objects are removed/object explicitly destroyed.
  3. __set(): It called when you try to set a property that is not accessible(not defined/public). If __set is used to set a property that is not exist, the new property will be public. If it is used on a property that is not public, the accessibility will not change.
  4.  __get():It called when try to access non accessible properties . Non-accessible means either the property is not defined or not public.If property is not defined then __get will be called from both inside and outside of the class context.You could even use it to set properties from outside the class.
  5.    __call(): It called when try to access not defined method.
  6.  __sleep(): It called when object is serialized with PHP’s serialize.It can be used to clean object before serialization.
  7. __wakeup():It called when object is un-serialized with PHP’s un-serialize.It can be used to reestablish resource like db connection.
  8.  __toString(): It called when you try to access object in string context. It cannot throw an exception-results in fatal error .If you will get any exceptions inside the __toSting then you need to handle inside itself.
  9.   __isset():  It called when isset is called on inaccessible property.
  10.  __unset(): It called when try to unset a non-accessible value.
  11.  __clone():  If clone is called on object that contains other object, both the clone and original contains same object.
  12.   __invoke(): It allows to treat an object like a function.
  13. __autoload(): It allow to auto load files automatically without require/require_once functions.

Disadvantages:

  • Magic code is hard to document and understand.
  • Magic methods do not support type hinting. One of the greatest advantages of using functions to set properties is that you can use type hinting.
  • Makes sure that the user property will always contain a valid user object or null.
  • IDEs do not support magic methods.