Tuesday, February 7, 2012

Information about Class, Abstract class and Interface

Abstract class:

Similarities with Class:
Abstract class is a type of class which can have all the ability of a Class.  Abstract class can have data members member functions, All Access Specifier like Private, Public and Protected, Constructor & Destructor.

Controversies with Class:

Abstract class cannot be instantiate with its own.  Abstract class data members, member functions can be called through only its derived classes.

Every normal methods within the Abstract class should have its function definition or body content.

Every abstract methods within the Abstract class shouldn't have its function definition or body content.  If we use function prefix with abstract keyword then the function is called as abstract function.  Private visibility is
not possible to create abstract function.  Public and protected will works function.  If an abstract class
abstract function is written in one class, then the derived class should have the function definition in it; else
error will be displayed.

Advantages of Abstract Class:


If we have a common functionality used throughout the application then we can use a certain data members and its member functions.  This data member, member function are optional for the derived class.  The derived class can use the abstract class or not.. that is depends on the class nature.

Only one abstract class can be inherited into a normal class using the keyword 'extends'.

Interface:

Similarity with Class:

Partially we can call the interface as class.

Controversies with Class:

Interface cannot be instantiate with its own.  Interface does not have data members but have member functions without function definition; just list abstract functions.

Every methods in Interface should be Public or blank access speficiers (Visibility).

We can inherit multiple interfaces into a normal class using the keyword as 'implements'

Hirarchy of inheriting:

If we want to inherit both abstract class and interface class then we need to inherit the abstract class at first
and can inherit 'N' number of interfaces into the normal class.

Exceptions:

We can inherit only abstract also into a normal class.
We can inherit only interface (1 or more interfaces) also into a normal class.

Example:


abstract class hisabstract {
    private $hismember1 = 'didnt_called_yet';
    const mymember1 = 'test';
   
    function __construct(){
        echo "
calling hisabstract constructor..";
    }
   
    public function hispublic (){
      $this->hisprivate();
        echo "
Previously called method is: ".$this->hismember1;
      echo "
i am in myabstract class";
      $this->hismember1 = __method__;
    }
   
    protected function hisprotected (){
      echo "
Previously called method is: ".$this->hismember1;
      echo "
i am in myabstract class with function name as : ".__function__;
        $this->hismember1 = __method__;
    }
   
    private function hisprivate(){
      echo "
Previously called method is: ".$this->hismember1;
      echo "
i am in myabstract class with function name as : ".__function__;
        $this->hismember1 = __method__;
    }
   
    function __destruct(){
        echo "
calling hisabstract destructor..";
    }
   
    abstract function hisabstract_memfunc();
   
    final function hisabstract_finalfunc(){
        echo "
function from hisabstract class .. it is actully a final function.";
    }
}

interface myinterface {
    public function mypublic ();
}

interface yourinterface {
    function yourpublic ();
}

class mano extends hisabstract implements myinterface, yourinterface {
    function mypublic(){
        echo "
calling hisabstract function definition..".$this->hisprotected();
        echo "
myinterface function definition..".$this->mymember1;
        $this->yourpublic();
       
        return $this;
    }
   
    function yourpublic(){
        echo "
yourinterface function definition..".$this->hispublic();
    }
   
    function hisabstract_memfunc(){
        echo "
his abstract class abstract function definition..";
        $this->hisabstract_finalfunc();
    }
}

$x = new mano;
$x->mypublic()->hisabstract_memfunc();

Friday, November 18, 2011

Optimize the tables in a Database using PHP

$alltables = db_query("SHOW TABLES");
while ($tablename = db_result($alltables)) {
  db_query("OPTIMIZE TABLE '".$tablename."'");
  echo $tablename." optimized now";
}
echo 'All tables optimized successfully';

Tuesday, September 27, 2011

Remove the Duplicate sub-Array element using PHP

/*
 * Function to Remove the Duplicate sub-Array element.
 */
function removeDuplicateArraybyElement(&$searchArray, $searchKey){
 
  /* Sorting the array values */
  objectSort($searchArray, $searchKey);
 
  /* Removing duplicate array values*/
  $searchBackupValue = "";
  $output = array ();
  foreach ($searchArray as $key => $sub_array){
      if ($searchBackupValue != $sub_array->$searchKey){
          $output[] = $sub_array;
      }
      $searchBackupValue = $sub_array->$searchKey;
  }
 
  $searchArray = $output;
}

Example with Drupal Code:

$products = taxonomy_get_tree(13, 0, -1, 1);
removeDuplicateArraybyElement($products, 'name');

Sunday, September 25, 2011

What is SSL and its purpose?

For most e-commerce sites, you absolutely need an SSL certificate!  As an online merchant, it is your responsibility to make sure the information you collect from your customers is protected. This will shield you and your customers by making sure that no one can intercept and misuse their credit card information.

If you accept credit card information and store it in a database so you can process it using an offline POS machine or charge it manually on your merchant account’s website, then you definitely need an SSL certificate to secure the credit card data as it is transferred. You also need to be very careful with the data when it is stored on your servers.

If your e-commerce site forwards your visitors to a 3rd party payment processor (like PayPal) to enter the credit card information then you don’t need an SSL certificate because your website won’t touch the credit card information.

If your users enter a username and password to login to your site without an SSL certificate, an attacker can easily see their username and password in clear text. This would allow someone else to impersonate your visitor, but it allows for a far more dangerous possibility:

If you have a login form or send or receive private customer information, then you need SSL. If you run an e-commerce website where people provide you with credit card information directly on your site, you absolutely need SSL.

Great! So you’re now sure that you need SSL for your e-commerce or other type of site.

How do i get a SSL Certificates?  Click here.

Trial SSL Certificates

Get a Free SSL Certificate from Comodo

  • Test your new site's SSL security certificate before it goes live.
  • See how easy it is to work with Comodo - Install your Certificate instantly.
  • Don't let your security lapse - get a free certificate and stay secure if your current cert is expiring soon.
  • Click here 

Tuesday, September 20, 2011

Object sort by Key value using PHP

/**
 * Function to swap two array with Values.
 * @param $&$data
 *   Array to be passed for swapping.
 * @param $key
 *   Filed name to be checked for
 * @return
 *   Swapped array.
 */
function objectSort(&$data, $key) {
  for ($i = count($data) - 1; $i >= 0; $i--) {
    $swapped = false;
    for ($j = 0; $j < $i; $j++) {
      if ($data[$j]->$key > $data[$j + 1]->$key){
        $tmp = $data[$j];
        $data[$j] = $data[$j + 1];
        $data[$j + 1] = $tmp;
        $swapped = true;
      }
    }
    if (!$swapped) return;
  }
}

Array sort by Key value using PHP

/**
 Here is a function to sort an array by the key of his sub-array.
*/
function arraySort(&$array, $subkey="id", $sort_ascending=false) {

    if (count($array))
        $temp_array[key($array)] = array_shift($array);

    foreach($array as $key => $val){
        $offset = 0;
        $found = false;
        foreach($temp_array as $tmp_key => $tmp_val)
        {
            if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
            {
                $temp_array = array_merge(    (array)array_slice($temp_array,0,$offset),
                                            array($key => $val),
                                            array_slice($temp_array,$offset)
                                          );
                $found = true;
            }
            $offset++;
        }
        if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
    }

    if ($sort_ascending) $array = array_reverse($temp_array);

    else $array = $temp_array;
}

Webservice in SOAP using PHP

What is SOAP?

SOAP, the Simple Object Access Protocol, is the powerhouse of web services. It’s a highly adaptable, object-oriented protocol that exists in over 80 implementations on every popular platform, including AppleScript, JavaScript, and Cocoa. It provides a flexible communication layer between applications, regardless of platform and location. As long as they both speak SOAP, a PHP-based web application can ask a C++ database application on another continent to look up the price of a book and have the answer right away. Another Internet Developer article shows how to use SOAP with AppleScript and Perl.

How SOAP works?

A SOAP transaction begins with an application making a call to a remote procedure. The SOAP client script then encodes the procedure request as an XML payload and sends it over the transport protocol to a server script. The server parses the request and passes it to a local method, which returns a response. The response is encoded as XML by the server and returned as a response to the client, which parses the response and passes the result to the original function.

SOAP versionings?

There are a number of different implementations of SOAP under PHP. It’s a shifting landscape: new ones appear, and old ones aren’t maintained or simply vanish. As of this writing, the most viable PHP implementation of SOAP seems to be Dietrich Ayala’s SOAPx4, also known as NuSOAP. This implementation is the most commonly used and appears to be the most fully developed and actively maintained, and it shows every sign of continuing to be a robust and popular solution. It’s not complete—a number of features, including full documentation, are still in the works—but it’s still a highly viable and easy-to-use SOAP solution.

Thursday, August 25, 2011

Google Finance API Sample PHP Code

/* Turn off notices for empty string values */
error_reporting(0);

/* Get data from google */
$data = file_get_contents('http://finance.google.com/finance/info?client=ig&q=NSE:BIRLAPOWER');

/* Strip first and last characters */
$data = substr($data,7,strlen($data)-7-4);

/* Split data into name:value records */
$records = explode(',', $data);

for($i = 0; $i < count($records); $i++) {
    /* split record into record name ($pair[0]) and record value ($pair[1]) */
    $pair = explode(": ", $records[$i]);
    /* do the output to be sure you got it right */
    echo 'Record name: ' . $pair[0] . ', Record value: ' . $pair[1] . '
';
}
?>

Thursday, August 11, 2011

Show / Hide Display errors in PHP

To Hide the Display errors:

error_reporting(0);
ini_set('display_errors','Off');

Tuesday, August 2, 2011

PHP functions for checking the Existance.

Function Existance:

function_exists();


Ex:


if (function_exists('imap_open')) {
    echo 
"IMAP functions are available.\n";
} else {
    echo 
"IMAP functions are not available.\n";
}


Method Existance:

Checks if the class method exists

class ParentClass {

   function
doParent() { }
}

class
ChildClass extends ParentClass { }

$p = new ParentClass();
$c = new ChildClass();

// all return true
var_dump(method_exists($p, 'doParent'));
var_dump(method_exists($c, 'doParent'));


File Existance:


Checks whether a file or directory exists

$filename = '/path/to/foo.txt';

if (
file_exists($filename)) {
    echo 
"The file $filename exists";
} else {
    echo 
"The file $filename does not exist";
}


Extension Existance: 


Find out whether an extension is loaded

if (!extension_loaded('gd')) {
    if (!
dl('gd.so')) {
        exit;
    }
}

Tuesday, June 28, 2011

Validating Multiple Checkbox with example

< ? for(..)?>
  < input type="checkbox" name="couponlist[]" value="couponId;?>" >
< ? }?>

Validation Script:
function validateRemove() {
    var chk = document.getElementsByName('couponlist[]');
    var len = chk.length;
    var flag = 0;
    for (i = 0; i < len; i++) {   
        if(    chk[i].checked == true ){
            flag = 1;
        }
    }
    if(flag == 1) {
        if(confirm('Are you sure you want to remove selected coupons')){
            document.forms.couponlist.submit();
        }
    } else {
        alert('Select atleast one coupon to remove');
        return false;
    }
}

Wednesday, June 15, 2011

Enabled drupal modules are showing as not enabled

Sometime this kind of problems will occur in drupal admin. At that time, we need to add the below line at the end of my.ini file to solve this problem.

max_allowed_packet = 32M


Note:
Step 1: paste the above line at the end of my.ini file
Step 2: restart your apache
Step 3: Check it and Enjoy
Step 4: if you are not an administrator user in your windows system, then you cant restart your apache, for that case you need to restart your windows system.

Thursday, June 9, 2011

Regular Expression with Different Validations

Regular expression examples for decimals input

Positive Integers --- ^\d+$
Negative Integers --- ^-\d+$
Integer --- ^-{0,1}\d+$
Positive Number --- ^\d*\.{0,1}\d+$
Negative Number --- ^-\d*\.{0,1}\d+$
Positive Number or Negative Number - ^-{0,1}\d*\.{0,1}\d+$
Phone number --- ^\+?[\d\s]{3,}$
Phone with code --- ^\+?[\d\s]+\(?[\d\s]{10,}$
Year 1900-2099 --- ^(19|20)[\d]{2,2}$
Date (dd mm yyyy, d/m/yyyy, etc.) --- ^([1-9]|0[1-9]|[12][0-9]|3[01])\D([1-9]|0[1-9]|1[012])\D(19[0-9][0-9]|20[0-9][0-9])$
IP v4 --- ^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]){3}$

Regular expression examples for Alphabetic input

Personal Name --- ^[\w\.\']{2,}([\s][\w\.\']{2,})+$
Username --- ^[\w\d\_\.]{4,}$
Password at least 6 symbols --- ^.{6,}$
Password or empty input --- ^.{6,}$|^$
email --- ^[\_]*([a-z0-9]+(\.|\_*)?)+@([a-z][a-z0-9\-]+(\.|\-*\.))+[a-z]{2,6}$
domain --- ^([a-z][a-z0-9\-]+(\.|\-*\.))+[a-z]{2,6}$

Other regular expressions
Match no input --- ^$
Match blank input --- ^\s[\t]*$
Match New line --- [\r\n]|$

Please, report any bugs to the author.

Tuesday, June 7, 2011

Purpose of MySQL INDEX with Example

MySQL Indexes

Using INDEX we can search and fetch the data from the table like getting a chapter or specific information from a book INDEX.

An index can be created in a table to find data more quickly and efficiently.

The users cannot see the indexes, they are just used to speed up searches/queries.

Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against.

SQL CREATE INDEX Syntax


Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name ON table_name (column_name)


SQL CREATE UNIQUE INDEX Syntax


Creates a unique index on a table. Duplicate values are not allowed:

CREATE UNIQUE INDEX index_name ON table_name (column_name)

Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the syntax for creating indexes in your database.

CREATE INDEX Example

The SQL statement below creates an index named "LastnameIndex" on the "LastName" column in the "Persons" table:

CREATE INDEX LastnameIndex ON Persons (LastName)


If you want to create an index on a combination of columns, you can list the column names within the parentheses, separated by commas:

CREATE INDEX LastandFirstnameIndex ON Persons (LastName, FirstName)

How MySQL Uses Indexes

Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.

Purpose of MySQL Index

Without INDEX:
If the number of records in a table is very less, then there is no need of using INDEX for a field in a table. Without INDEX also it will work very fast with less records table.

With INDEX:
If we want to know the real purpose of the MySQL INDEX when the records is more than 1000 records (say for example). Our system will get slow to fetch the records.

We can solve this problem by using several methods like:
a. Increase the memory_limit in our server
b. Increase the maximum_execution_time in our server
c. Optimize the Query like fetching the appropriate fields instead of Select * from ... etc..

But, We cant increase our System performance. So, now the time to introduce INDEX.

The performance of the table is really improve when using INDEX.

Regular Expressions - User Guide

Simple Matching

::Example::

STRING1 Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)
STRING2 Mozilla/4.75 [en](X11;U;Linux2.2.16-22 i586)


Search for

m
STRING1 match Finds the m in compatible
STRING2 no match There is no lower case m in this string. Searches are case sensitive unless you take special action.

a/4
STRING1 match Found in Mozilla/4.0 - any combination of characters can be used for the match
STRING2 match Found in same place as in STRING1

5 [
STRING1 no match The search is looking for a pattern of '5 [' and this does NOT exist in STRING1. Spaces are valid in searches.
STRING2 match Found in Mozilla/4.75 [en]

in
STRING1 match found in Windows
STRING2 match Found in Linux

le
STRING1 match found in compatible
STRING2 no match There is an l and an e in this string but they are not adjacent (or contiguous).

[ ]

Match anything inside the square brackets for ONE character position once and only once, for example, [12] means match the target to 1 and if that does not match then match the target to 2 while [0123456789] means match to any character in the range 0 to 9.

-

The - (dash) inside square brackets is the 'range separator' and allows us to define a range, in our example above of [0123456789] we could rewrite it as [0-9].

You can define more than one range inside a list, for example, [0-9A-C] means check for 0 to 9 and A to C (but not a to c).

NOTE: To test for - inside brackets (as a literal) it must come first or last, that is, [-0-9] will test for - and 0 to 9.

^

The ^ (circumflex or caret) inside square brackets negates the expression (we will see an alternate use for the circumflex/caret outside square brackets later), for example, [^Ff] means anything except upper or lower case F and [^a-z] means everything except lower case a to z.

in[du]
STRING1 match finds ind in Windows
STRING2 match finds inu in Linux

x[0-9A-Z]
STRING1 no match Again the tests are case sensitive to find the xt in DigExt we would need to use [0-9a-z] or [0-9A-Zt]. We can also use this format for testing upper and lower case e.g. [Ff] will check for lower and upper case F.
STRING2 match Finds x2 in Linux2

[^A-M]in
STRING1 match Finds Win in Windows
STRING2 no match We have excluded the range A to M in our search so Linux is not found but linux (if it were present) would be found.

?

The ? (question mark) matches the preceding character 0 or 1 times only, for example, colou?r will find both color (0 times) and colour (1 time).

*

The * (asterisk or star) matches the preceding character 0 or more times, for example, tre* will find tree (2 times) and tread (1 time) and trough (0 times).

+

The + (plus) matches the previous character 1 or more times, for example, tre+ will find tree (2 times) and tread (1 time) but not trough (0 times).

{n}

Matches the preceding character, or character range, n times exactly, for example, to find a local phone number we could use [0-9]{3}-[0-9]{4} which would find any number of the form 123-4567.

Regular Expression in PHP with Examples

more info.. http://evergreenphp.blogspot.com

What is a Regular Expression?

A regular expression is a set of characters that specify a pattern. The term "regular" has nothing to do with a high-fiber diet. It comes from a term used to describe grammars and formal languages.

Regular expressions are used when you want to search for specify lines of text containing a particular pattern. Most of the UNIX utilities operate on ASCII files a line at a time. Regular expressions search for patterns on a single line, and not for patterns that start on one line and end on another.

It is simple to search for a specific word or string of characters. Almost every editor on every computer system can do this. Regular expressions are more powerful and flexible. You can search for words of a certain size. You can search for a word with four or more vowels that end with an "s". Numbers, punctuation characters, you name it, a regular expression can find it. What happens once the program you are using find it is another matter. Some just search for the pattern. Others print out the line containing the pattern. Editors can replace the string with a new pattern. It all depends on the utility.

Regular expressions confuse people because they look a lot like the file matching patterns the shell uses. They even act the same way--almost. The square brackers are similar, and the asterisk acts similar to, but not identical to the asterisk in a regular expression. In particular, the Bourne shell, C shell, find, and cpio use file name matching patterns and not regular expressions.

Remember that shell meta-characters are expanded before the shell passes the arguments to the program. To prevent this expansion, the special characters in a regular expression must be quoted when passed as an option from the shell. You already know how to do this because I covered this topic in last month's tutorial.

The Structure of a Regular Expression

There are three important parts to a regular expression. Anchors are used to specify the position of the pattern in relation to a line of text. Character Sets match one or more characters in a single position. Modifiers specify how many times the previous character set is repeated. A simple example that demonstrates all three parts is the regular expression "^#*". The up arrow is an anchor that indicates the beginning of the line. The character "#" is a simple character set that matches the single character "#". The asterisk is a modifier. In a regular expression it specifies that the previous character set can appear any number of times, including zero. This is a useless regular expression, as you will see shortly.

There are also two types of regular expressions: the "Basic" regular expression, and the "extended" regular expression. A few utilities like awk and egrep use the extended expression. Most use the "regular" regular expression. From now on, if I talk about a "regular expression," it describes a feature in both types.

Here is a table of the Solaris (around 1991) commands that allow you to specify regular expressions:
Utility Regular Expression Type
vi Basic
sed Basic
grep Basic
csplit Basic
dbx Basic
dbxtool Basic
more Basic
ed Basic
expr Basic
lex Basic
pg Basic
nl Basic
rdist Basic
awk Extended
nawk Extended
egrep Extended
EMACS EMACS Regular Expressions
PERL PERL Regular Expressions

The Anchor Characters: ^ and $

Most UNIX text facilities are line oriented. Searching for patterns that span several lines is not easy to do. You see, the end of line character is not included in the block of text that is searched. It is a separator. Regular expressions examine the text between the separators. If you want to search for a pattern that is at one end or the other, you use anchors. The character "^" is the starting anchor, and the character "$" is the end anchor. The regular expression "^A" will match all lines that start with a capital A. The expression "A$" will match all lines that end with the capital A. If the anchor characters are not used at the proper end of the pattern, then they no longer act as anchors. That is, the "^" is only an anchor if it is the first character in a regular expression. The "$" is only an anchor if it is the last character. The expression "$1" does not have an anchor. Neither is "1^". If you need to match a "^" at the beginning of the line, or a "$" at the end of a line, you must escape the special characters with a backslash. Here is a summary:
Pattern Matches
^A "A" at the beginning of a line
A$ "A" at the end of a line
A^ "A^" anywhere on a line
$A "$A" anywhere on a line
^^ "^" at the beginning of a line
$$ "$" at the end of a line

The use of "^" and "$" as indicators of the beginning or end of a line is a convention other utilities use. The vi editor uses these two characters as commands to go to the beginning or end of a line. The C shell uses "!^" to specify the first argument of the previous line, and "!$" is the last argument on the previous line.

It is one of those choices that other utilities go along with to maintain consistancy. For instance, "$" can refer to the last line of a file when using ed and sed. Cat -e marks end of lines with a "$". You might see it in other programs as well.

Matching a character with a character set

The simplest character set is a character. The regular expression "the" contains three character sets: "t," "h" and "e". It will match any line with the string "the" inside it. This would also match the word "other". To prevent this, put spaces before and after the pattern: " the ". You can combine the string with an anchor. The pattern "^From: " will match the lines of a mail message that identify the sender. Use this pattern with grep to print every address in your incoming mail box:

grep '^From: ' /usr/spool/mail/$USER

Some characters have a special meaning in regular expressions. If you want to search for such a character, escape it with a backslash.

Match any character with .

The character "." is one of those special meta-characters. By itself it will match any character, except the end-of-line character. The pattern that will match a line with a single characters is

^.$

Specifying a Range of Characters with [...]

If you want to match specific characters, you can use the square brackets to identify the exact characters you are searching for. The pattern that will match any line of text that contains exactly one number is

^[0123456789]$

This is verbose. You can use the hyphen between two characters to specify a range:

^[0-9]$

You can intermix explicit characters with character ranges. This pattern will match a single character that is a letter, number, or underscore:

[A-Za-z0-9_]

Character sets can be combined by placing them next to each other. If you wanted to search for a word that

1. Started with a capital letter "T".
2. Was the first word on a line
3. The second letter was a lower case letter
4. Was exactly three letters long, and
5. The third letter was a vowel

the regular expression would be "^T[a-z][aeiou] ".

Exceptions in a character set

You can easily search for all characters except those in square brackets by putting a "^" as the first character after the "[". To match all characters except vowels use "[^aeiou]".

Like the anchors in places that can't be considered an anchor, the characters "]" and "-" do not have a special meaning if they directly follow "[". Here are some examples:
Regular Expression Matches
[] The characters "[]"
[0] The character "0"
[0-9] Any number
[^0-9] Any character other than a number
[-0-9] Any number or a "-"
[0-9-] Any number or a "-"
[^-0-9] Any character except a number or a "-"
[]0-9] Any number or a "]"
[0-9]] Any number followed by a "]"
[0-9-z] Any number,
or any character between "9" and "z".
[0-9\-a\]] Any number, or
a "-", a "a", or a "]"

Repeating character sets with *

The third part of a regular expression is the modifier. It is used to specify how may times you expect to see the previous character set. The special character "*" matches zero or more copies. That is, the regular expression "0*" matches zero or more zeros, while the expression "[0-9]*" matches zero or more numbers.

This explains why the pattern "^#*" is useless, as it matches any number of "#'s" at the beginning of the line, including zero. Therefore this will match every line, because every line starts with zero or more "#'s".

At first glance, it might seem that starting the count at zero is stupid. Not so. Looking for an unknown number of characters is very important. Suppose you wanted to look for a number at the beginning of a line, and there may or may not be spaces before the number. Just use "^ *" to match zero or more spaces at the beginning of the line. If you need to match one or more, just repeat the character set. That is, "[0-9]*" matches zero or more numbers, and "[0-9][0-9]*" matches one or more numbers.

Matching a specific number of sets with \{ and \}

You can continue the above technique if you want to specify a minimum number of character sets. You cannot specify a maximum number of sets with the "*" modifier. There is a special pattern you can use to specify the minimum and maximum number of repeats. This is done by putting those two numbers between "\{" and "\}". The backslashes deserve a special discussion. Normally a backslash turns off the special meaning for a character. A period is matched by a "\." and an asterisk is matched by a "\*".

If a backslash is placed before a "<," ">," "{," "}," "(," ")," or before a digit, the backslash turns on a special meaning. This was done because these special functions were added late in the life of regular expressions. Changing the meaning of "{" would have broken old expressions. This is a horrible crime punishable by a year of hard labor writing COBOL programs. Instead, adding a backslash added functionality without breaking old programs. Rather than complain about the unsymmetry, view it as evolution.

Having convinced you that "\{" isn't a plot to confuse you, an example is in order. The regular expression to match 4, 5, 6, 7 or 8 lower case letters is

[a-z]\{4,8\}

Any numbers between 0 and 255 can be used. The second number may be omitted, which removes the upper limit. If the comma and the second number are omitted, the pattern must be duplicated the exact number of times specified by the first number.

Thursday, May 12, 2011

Objects and References

more info.. http://evergreenphp.blogspot.com

Objects and references
One of the key-points of PHP5 OOP that is often mentioned is that "objects are passed by references by
default". This is not completely true. This section rectifies that general thought using some examples.
A PHP reference is an alias, which allows two different variables to write to the same value. As of
PHP5, an object variable doesn't contain the object itself as value anymore. It only contains an object
identifier which allows object accessors to find the actual object. When an object is sent by argument,
returned or assigned to another variable, the different variables are not aliases: they hold a copy of the
identifier, which points to the same object.

$b->foo= 2;
echo $a->foo."\n";
$c = new A;
$d= &$c;
// $c and $d are references
// ($c,$d) = < id >
$d->foo= 2;
echo$c->foo."\n";
$e = new A;
functionfoo($obj) {
// ($obj) = ($e) = < id >
$obj->foo= 2;
}foo($e);
echo$e->foo."\n";
?>

Type Hinting

more info.. http://evergreenphp.blogspot.com

Type Hinting
PHP 5 introduces Type Hinting. Functions are now able to force parameters to be objects (by
specifying the name of the class in the function prototype) or arrays (since PHP 5.1). However, if
NULL is used as the default parameter value, it will be allowed as an argument for any later call.
var;
}/**
* Another test function
** First parameter must be an array
*/
public functiontest_array(array$input_array) {
print_r($input_array);
}
}// Another example class
classOtherClass {
public$var = 'Hello World';
}?>

Final Keyword

more info.. http://evergreenphp.blogspot.com

Final Keyword
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by
prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

Object Cloning

more info.. http://evergreenphp.blogspot.com

Object Cloning
Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good
example of the need for copy constructors, is if you have an object which represents a GTK window
and the object holds the resource of this GTK window, when you create a duplicate you might want to
create a new window with the same properties and have the new object hold the resource of the new
window. Another example is if your object holds a reference to another object which it uses and when
you replicate the parent object you want to create a new instance of this other object so that the replica
has its own separate copy.
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.
$copy_of_object = clone $object;
When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any
properties that are references to other variables, will remain references.
Once the cloning is complete, if a __clone() method is defined, then the newly created object's
__clone() method will be called, to allow any necessary properties that need to be changed.
instance = ++self::$instances;
}public function__clone() {
$this->instance = ++self::$instances;
}
}classMyCloneable
{
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);
?>