Categories
PHP

9 Magic Methods for PHP

The “magic” methods are ones with special names, starting with two underscores, which denote methods which will be triggered in response to particular PHP events.

That might sound slightly automagical but actually it’s pretty straightforward, we already saw an example of this in the last post, where we used a constructor – so we’ll use this as our first example.

__construct

The constructor is a magic method that gets called when the object is instantiated. It is usually the first thing in the class declaration but it does not need to be, it is a method like any other and can be declared anywhere in the class.

Constructors also inherit like any other method. So if we consider our previous inheritance example from the Introduction to OOP, we could add a constructor to the Animal class like this:

class Animal {

  public function __construct() {
    $this->created = time();
    $this->logfile_handle = fopen('/tmp/log.txt', 'w');
  }

}

animal.php

Now we can create a class which inherits from the Animal class – a Penguin! Without adding anything into the Penguin class, we can declare it and have it inherit from Animal, like this:

class Penguin extends Animal {

}

$tux = new Penguin;
echo $tux->created;

If we define a __construct method in the Penguin class, then Penguin objects will run that instead when they are instantiated. Since there isn’t one, PHP looks to the parent class definition for information and uses that. So we can override, or not, in our new class – very handy.

__destruct

Did you spot the file handle that was also part of the constructor? We don’t really want to leave things like that lying around when we finish using an object and so the __destruct method does the opposite of the constructor. It gets run when the object is destroyed, either expressly by us or when we’re not using it any more and PHP cleans it up for us. For the Animal, our __destruct method might look something like this:

class Animal{

  public function __construct() {
    $this->created = time();
    $this->logfile_handle = fopen('/tmp/log.txt', 'w');
  }

  public function __destruct() {
    fclose($this->logfile_handle);
  }
}

animal2.php

The destructor lets us close up any external resources that were being used by the object. In PHP since we have such short running scripts (and look out for greatly improved garbage collection in newer versions), often issues such as memory leaks aren’t a problem. However it’s good practice to clean up and will give you a more efficient application overall!

__get

This next magic method is a very neat little trick to use – it makes properties which actually don’t exist appear as if they do. Let’s take our little penguin:

class Penguin extends Animal {

  public function __construct($id) {
    $this->getPenguinFromDb($id);
  }

  public function getPenguinFromDb($id) {
    // elegant and robust database code goes here
  }
}

penguin1.php

Now if our penguin has the properties “name” and “age” after it is loaded, we’d be able to do:

$tux = new Penguin(3);
echo $tux->name . " is " . $tux->age . " years old\n";

However imagine something changed about the backend database or information provider, so instead of “name”, the property was called “username”. And imagine this is a complex application which refers to the “name” property in too many places for us to change. We can use the __get method to pretend that the “name” property still exists:

class Penguin extends Animal {

  public function __construct($id) {
    $this->getPenguinFromDb($id);
  }

  public function getPenguinFromDb($id) {
    // elegant and robust database code goes here
  }

  public function __get($field) {
    if($field == 'name') {
      return $this->username;
    }
}

penguin2.php

This technique isn’t really a good way to write whole systems, because it makes code hard to debug, but it is a very valuable tool. It can also be used to only load properties on demand or show calculated fields as properties, and a hundred other applications that I haven’t even thought of!

__set

So we updated all the calls to $this->name to return $this->username but what about when we want to set that value, perhaps we have an account screen where users can change their name? Help is at hand in the form of the __set method, and easiest to illustrate with an example.

class Penguin extends Animal {

  public function __construct($id) {
    $this->getPenguinFromDb($id);
  }

  public function getPenguinFromDb($id) {
    // elegant and robust database code goes here
  }

  public function __get($field) {
    if($field == 'name') {
      return $this->username;
    }
  }

  public function __set($field, $value) {
    if($field == 'name') {
      $this->username = $value;
    }
  }
}

penguin3.php

In this way we can falsify properties of objects, for any one of a number of uses. As I said, not a way to build a whole system, but a very useful trick to know.

__call

There are actually two methods which are similar enough that they don’t get their own title in this post! The first is the __call method, which gets called, if defined, when an undefined method is called on this object.

The second is __callStatic which behaves in exactly the same way but responds to undefined static method calls instead (only in new versions though, this was added in PHP 5.3).

Probably the most common thing I use __call for is polite error handling, and this is especially useful in library code where other people might need to be integrating with your methods.

So for example if a script had a Penguin object called $penguin and it contained $penguin->speak() ... the speak() method isn’t defined so under normal circumstances we’d see:

PHP Fatal error: Call to undefined method Penguin::speak() in …

What we can do is add something to cope more nicely with this kind of failure than the PHP fatal error you see here, by declaring a method __call. For example:

class Animal {
}
class Penguin extends Animal {

  public function __construct($id) {
    $this->getPenguinFromDb($id);
  }

  public function getPenguinFromDb($id) {
    // elegant and robust database code goes here
  }

  public function __get($field) {
    if($field == 'name') {
      return $this->username;
    }
  }

  public function __set($field, $value) {
    if($field == 'name') {
      $this->username = $value;
    }
  }

  public function __call($method, $args) {
      echo "unknown method " . $method;
      return false;
  }
}

penguin4.php

This will catch the error and echo it. In a practical application it might be more appropriate to log a message, redirect a user, or throw an exception, depending on what you are working on – but the concept is the same.

Any misdirected method calls can be handled here however you need to, you can detect the name of the method and respond differently accordingly – for example you could handle method renaming in a similar way to how we handled the property renaming above.

__sleep

The __sleep() method is called when the object is serialised, and allows you to control what gets serialised. There are all sorts of applications for this, a good example is if an object contains some kind of pointer, for example a file handle or a reference to another object.

When the object is serialised and then unserialised then these types of references are useless since the target may no longer be present or valid. Therefore it is better to unset these before you store them.

__wakeup

This is the opposite of the __sleep() method and allows you to alter the behaviour of the unserialisation of the object. Used in tandem with __sleep(), this can be used to reinstate handles and object references which were removed when the object was serialised.

A good example application could be a database handle which gets unset when the item is serialised, and then reinstated by referring to the current configuration settings when the item is unserialised.

__clone

We looked at an example of using the clone keyword in the second part of my introduction to OOP in PHP, to make a copy of an object rather than have two variables pointing to the same actual data. By overriding this method in a class, we can affect what happens when the clone keyword is used on this object.

While this isn’t something we come across every day, a nice use case is to create a true singleton by adding a private access modifier to the method.

__toString

Definitely saving the best until last, the __toString method is a very handy addition to our toolkit. This method can be declared to override the behaviour of an object which is output as a string, for example when it is echoed.

For example if you wanted to just be able to echo an object in a template, you can use this method to control what that output would look like. Let’s look at our Penguin again:

class Penguin {

  public function __construct($name) {
      $this->species = 'Penguin';
      $this->name = $name;
  }

  public function __toString() {
      return $this->name . " (" . $this->species . ")\n";
  }
}

penguin5.php

With this in place, we can literally output the object by calling echo on it, like this:

$tux = new Penguin('tux');
echo $tux;

I don’t use this shortcut often but it’s useful to know that it is there.

More Magic Methods

There is a great reference on the php.net site itself, listing all the available magic methods (yes, there are more than these, I just picked the ones I actually use) so if you want to know what else is available then take the time to check this out.

Hopefully this has been a useful introduction to the main ones, leave a comment to let us know how you use these in your own projects!

'Coz sharing is caring
Categories
BFSI Income

Decoding IFSC code

IFSC Code is Indian Financial System Code, which is an eleven character code assigned by RBI to identify every bank branches uniquely, that are participating in NEFT system in India. This code is used by electronic payment system applications such as RTGS, ,National Electronic Fund Transfer and CFMS.

The code is of 11 characters. The first part is the first 4 alphabet characters representing the Bank. Next character is 0(zero), this is reserved for future use. The branch code is the last six characters. To know what is IFSC Code deeply, go through the article fully. Otherwise, if you need IFSC Code of any branch, just follow the instructions below.
How to find IFSC code?
Normally, this 11 digit code will be printed on cheque book for NEFT enabled banks. Also, you can find bank IFSC code, bank details, branch address for all banks in India by following link. By using 4 steps you can easily find this code and branch location.
IFSC Code 
1. Select your Bank (eg : State Bank of India)
2. Select your State
3. Select your District
4. Select your Branch name – Now you can find IFSC Code, MICR Code, Address and Contact phone number of your bank branch.
Reserve Bank of India (RBI)
RBI is the central banking institution of India which controls Indian rupee and all banks. It controls inter bank money transfer in all over India banks through RTGS and NEFT. It was established in April 1, 1935 and nationalized in 1949. Reserve Bank of India is fully owned by government of India.

Functions of RBI

1. Authority in monetary

RBI monitors and implements the monetary policy which maintains price stability in productive sectors.

2. Maintain financial system

It manages country’s financial and banking system which provides cost-effective banking solutions to customers.

3. Foreign exchange management

Reserve Bank of India facilitates to maintain foreign exchange and trade FOREX (foreign exchange) market in India.

4. Currency issuer

Reserve Bank of India issues / exchanges / destroys currency notes and coins in India.

5. Role of development

RBI operates wide range of development functions to achieve national goals.

6. Other functions

RBI maintains all merchant banking account for state and central banks.

RTGS (Real Time Gross Settlement) brief explanation

RTGS (Real Time Gross Settlement) is a fund transfer system used to transfer money from one bank to another. This gross basis transfer is a real time transfer system. This system can performs for large value of transaction, minimum amount can be transferred is Rs.2,00,000. There is no maximum amount limit for this transaction.

Time taken for transferring funds

The time taken for receiving funds to beneficiary account in real time when the remitting bank transferred funds. The remitting customer can receive acknowledgment from RBI when the funds transferred.

RTGS process

Normally RBI allows to use four flow structure (V, Y, L, T) in fund transfer. In RTGS system, RBI decided to use Y shaped flow structure in this system. The following flows of instructions are used in this structure.
1. The remitting bank will be send payment instruction to central processer’s technical operator
2. The central processor acknowledge stripping of message and sending original message with set of instructions (what the amount to be transferred, what is IFSC code of branch, issuing and receiving banks identification etc.) to central bank
3. The central bank process debit of remitting bank’s account and credit to beneficiary bank’s account. After transaction completed then, sending confirmation to central processor
4. The central processor re-constructing of payment message with stripped information (beneficiary details) and sending message to receiving bank with proper details

RTGS processing/service charges

Transaction Charges
Inward transactions Free, no charges
Outward transactions

a] 2 lakhs to 5 lakhs
b] Above 5 lakhs
Not exceeding Rs.25
Not exceeding Rs.50

Benefits of RTGS

Real time fund transfer

All transactions are processed and settled in real time basis.

Credit risk eliminated

There is no credit and liquidity risks in RTGS payment system. The beneficiary bank customer can receive payment instantly when the central bank system accepted request.

Efficiency of economy

Without exposing settlement risk, the payments are ensuring quick and secure in financial market transactions and major business solution.

RTGS coverage

The RTGS payment system was launched on 26th, March 2004 by RBI with involving four banks only. Presently it covers 109 banks in 13750 branches and 508 clearing centers. More than 800 cities/towns are covered for customer transaction.

NEFT (National Electronic Fund Transfer) brief explanation

NEFT (National Electronic Fund Transfer) is an online national-wide fund transfer system supported by RBI. It is used by an individual, firm and corporate to transfer payment as electronically. NEFT is used for small and medium amount transfer between banks and accounts. No minimum amount limit for NEFT.

Time taken for transferring funds

NEFT process to transfer funds on hourly batches. In week days there are 11 settlements (starts at 9 A.M and ends at 7 P.M) and in Saturday there are 5 settlements (starts at 9 A.M ends at 1 P.M). Normally the payment will be send to the RBI within 3 hours when remitting account given request for transaction. The actual time to take transaction completed depends on beneficiary bank to process the funds.

NEFT process

In this payment system process payment transfer from remitting account to beneficiary account involved 5 levels of operations. They are,

Level 1:

If anyone (corporate, firm or individual) likes to transfer their funds from their remitting account to beneficiary account through NEFT payment system, they need to fill the form with beneficiary account details (beneficiary account holder name, account number, what is IFSC code of branch, maximum amount to transfer and account type). This application form can available from all banking branches. Customers can available facility to transfer their funds through online by using internet banking and mobile banking facilities. Some banks are offers to use NEFT transfer by using their ATMs. The remitting customer can authorize transfer specified amount to beneficiary account.

Level 2:

The remitting bank branch begains with payment transfer message and send it to NEFT service centre.

Level 3:

The service centre stripping message and forward to NEFT clearing centre (controlled by RBI) with details of next batch available to transfer payment.

Level 4:

The NEFT clearing centre ascending fund transfer requests as beneficiary bank-wise. Then creates payment entries to debit funds from remitting banks and credit payments to beneficiary banks. Also, NEFT service centre sends response messages to destination bank-wise.

Level 5:

The acceptance message receives destination banks from NEFT clearing centre and transfer credit to beneficiary account.

NEFT processing/service charges

From March 31, 2011 RBI refrain from insisting the processing/service charges to member banks. So, member banks who are participating in NEFT fund transfer no need to pay any charges to RBI. The following charges are rationalized under RBI.

Beneficiary bank’s inward transaction:

No need to pay any charges from beneficiaries for payment transfer to destination accounts.

Beneficiary bank’s outward transaction:

Transaction Charges (+service tax)
Below Rs.1 lakh Rs.5
Rs.1 lakh and up to Rs.2 lakhs Rs.15
Above 2lakhs Rs.25

Payment transfer from India to Nepal:

Transaction Charges (+service tax)
Remitting banks from India Upto Rs.5
SBI (if beneficiary account maintained with Nepal SBI Ltd. (NSBL) Upto Rs.20
SBI (if shares this same fund with NSBL) No charges
Beneficiary branch not maintained accoumt with NSBL Rs.50 (transfer up to Rs.5000)

Rs.75 (transfer above Rs.5000)

Benefits of NEFT:

Eco-friendly:

The total process of NEFT is eco-friendly and drastically reduce paperwork.

Secure and efficient:

This system performs seamless transfer of funds from one bank to another. During the transaction there are no chances to occur mistakes and whole operation is said to be quick and highly secure.

Economic efficiency:

NEFT fund transfer service charge is much less instead of making transfer by using pay order or demand draft.

Risk free transfer:

There is no credit and liquidity risks in NEFT payment system. The fund transfer request is processed and settled in day’s time.

RTGS Vs NEFT

When compared to RTGS and NEFT, RTGS payment transfer system based on gross settlement and NEFT payment transfer system based on net settlement. Gross settlement is known as transaction held without bouncing other transaction on one-to-one basis.Net settlement is known as transaction completed in specific time of batches.
Basically RTGS fund transfer used for large amount of transaction, the minimum amount can be 2 lakhs. In NEFT system can allows to transfer small amount of funds, there is no minimum value.
Reading What is MICR Code, What is SWIFT Code and What is IBAN number… will make more understanding.
'Coz sharing is caring