Article

Creating a Credit Card Validation Class With PHP

Page: 1 2 3 4 5 6 7 Next

Whenever we want to create a new instance of our CCreditCard class, we must explicitly pass in five arguments to its constructor: the cardholder's name, card type, number, and expiry date. Because we have created our own custom constructor (PHP implements a default constructor that accepts no arguments if we don't explicitly create one), we must pass in values for each of these five arguments every time we instantiate the class. If we omit them, PHP will raise an error.

// Constructor  
function CCreditCard($name, $type, $num, $expm, $expy)  
{

If the value of the $name variable passed into the constructor is empty, then we use the die() function to terminate the instantiation of our class and output an error message telling the user that they must pass a name to the constructor:

// Set member variables  
if(!empty($name))  
{  
$this->__ccName = $name;  
}  
else  
{  
die('Must pass name to constructor');  
}

Our CCreditCard class is flexible: it accepts several different ways to specify the type of card that is being stored. For example, if we want to add the details of a mastercard to a new instance of our CCreditCard class, then we could pass in the following values for the $type variable of the constructor: "mc", "mastercard", "m", or "1".

We make sure that a valid card type has been passed in, and set the value of our classes $__ccType variable to one of the constant card type values that we defined earlier:

// Make sure card type is valid  
switch(strtolower($type))  
{  
  case 'mc':  
  case 'mastercard':  
  case 'm':  
  case '1':  
    $this->__ccType = CARD_TYPE_MC;  
    break;  
  case 'vs':  
  case 'visa':  
  case 'v':  
  case '2':  
    $this->__ccType = CARD_TYPE_VS;  
    break;  
  case 'ax':  
  case 'american express':  
  case 'a':  
  case '3':  
    $this->__ccType = CARD_TYPE_AX;  
    break;  
  case 'dc':  
  case 'diners club':  
  case '4':  
    $this->__ccType = CARD_TYPE_DC;  
    break;  
  case 'ds':  
  case 'discover':  
  case '5':  
    $this->__ccType = CARD_TYPE_DS;  
    break;  
  case 'jc':  
  case 'jcb':  
  case '6':  
    $this->__ccType = CARD_TYPE_JC;  
    break;  
  default:  
    die('Invalid type ' . $type . ' passed to constructor');  
}

If an invalid card type is passed in, then the default branch of our switch statement will be called, resulting in our script terminating with the die() function.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links