Its My Space

Cooooooooooool

Archive for the ‘PHP’ Category

PHP

HOW TO ANSWER TOUGH INTERVIEW QUESTIONS

Posted by Ramkumar on April 1, 2009

There’s no worse feeling than when you’re in an interview and the interviewer asks you a question to which you don’t know the answer. The best way to handle this dreaded debacle is to go into the interview prepared. Familiarize yourself with a few common difficult questions and arm yourself with answers prepared ahead of time.
Check out these tough interview questions and some suggested responses in order to avoid an interview disaster:

Tough question No. 1: “Tell me about yourself.”
This is usually the opening question in an interview and it’s the perfect moment for you to toot your own horn — not to tell your life history. Your answers should be a quick rundown of your qualifications and experience. Talk about your education, work history, recent career experience and future goals.
Suggested answer: “I graduated from University X and since then, I have been working in public relations with an agency where I have generated millions of PR hits for my clients. While I’ve enjoyed working on the agency side, I’m looking to expand my horizons and start doing PR for corporate companies such as this one.”

Tough question No. 2: “Why did you leave your last job?”
This is your chance to talk about your experience and your career goals, not to badmouth a former boss or give a laundry list of reasons for your exit. Instead, focus on what you learned in your previous position and how you are ready to use those skills in a new position.
Suggested answer: “The company just wasn’t a good fit for my creativity, but I learned that organizations have distinct personalities just like people do. Now I know where I’ll be a better fit.”

Tough question No. 3: “Where do you see yourself in five years?”
Let the employer know that you’re stable and you want to be with this company for the long haul. Keep your aspirations to take over the firm with which you are interviewing, own your own company, retire at 40 or be married with five children to yourself.
Suggested answer: “I want to secure a civil engineering position with a national firm that concentrates on retail development. Ideally, I would like to work for a young company, such as this one, so I can get in on the ground floor and take advantage of all the opportunities a growing firm has to offer.”

Tough question No. 4: “What are your weaknesses?”
The key to answering this age-old question is not to respond literally. Your future employer most likely won’t care if your weak spot is that you can’t cook, nor do they want to hear the generic responses, like you’re “too detail oriented” or “work too hard.” Respond to this query by identifying areas in your work where you can improve and figure out how they can be assets to a future employer. If you didn’t have the opportunity to develop certain skills at your previous job, explain how eager you are to gain that skill in a new position.
Suggested answer: “In my last position, I wasn’t able to develop my public-speaking skills. I’d really like to be able to work in a place that will help me get better at giving presentations and talking in front of others.”

Tough question No. 5: “Why were you laid off?”
This question will become more common as the economy continues to slow down. It’s a tough question, however, especially because many workers aren’t told exactly why they were laid off. The best way to tackle this question is to answer as honestly as possible.
Suggested answer: “As I’m sure you’re aware, the economy is tough right now and my company felt the effects of it. I was part of a large staff reduction and that’s really all I know. I am confident, however, that it had nothing to do with my job performance, as exemplified by my accomplishments. For example…”

Tough question No. 6: “Tell me about the worst boss you ever had.”
Never, ever talk badly about your past bosses. A potential boss will anticipate that you’ll talk about him or her in the same manner somewhere down the line.
Suggested answer: “While none of my past bosses were awful, there are some who taught me more than others did. I’ve definitely learned what types of management styles I work with the best.”

Tough question No. 7: How would others describe you?
You should always be asking for feedback from your colleagues and supervisors in order to gauge your performance; this way, you can honestly answer the question based on their comments. Keep track of the feedback to be able to give to an employer, if asked. Doing so will also help you identify strengths and weaknesses.
Suggested answer: “My former colleagues have said that I’m easy to do business with and that I always hit the ground running with new projects. I have more specific feedback with me, if you’d like to take a look at it.”

Tough question No. 8: “What can you offer me that another person can’t?”
This is when you talk about your record of getting things done. Go into specifics from your résumé and portfolio; show an employer your value and how you’d be an asset.
Suggested answer: “I’m the best person for the job. I know there are other candidates who could fill this position, but my passion for excellence sets me apart from the pack. I am committed to always producing the best results. For example…”

Tough question No. 9: “If you could choose any company to work for, where would you go?”
Never say that you would choose any company other than the one where you are interviewing. Talk about the job and the company for which you are being interviewed.
Suggested answer: “I wouldn’t have applied for this position if I didn’t sincerely want to work with your organization. ” Continue with specific examples of why you respect the company with which you are interviewing and why you’ll be a good fit.

Tough question No. 10: “Would you be willing to take a salary cut?”
Salary is a delicate topic. In today’s tough economy though, how much a company can afford to pay you might be the deal breaker in whether or not you are offered a position.
Suggested answer: “I’m making $X now. I understand that the salary range for this position is $XX – $XX. Like most people, I would like to improve on my salary, but I’m more interested in the job itself than the money. I would be open to negotiating a lower starting salary but would hope that we can revisit the subject in a few months after I’ve proved myself to you.”

Posted in General, Interview Questions, Technology | Tagged: , | 1 Comment »

Date Time Functions in php

Posted by Ramkumar on February 13, 2009

checkdate() : Validates a Gregorian date

date_default_timezone_get() : Returns the default time zone

date_default_timezone_set() : Sets the default time zone

date_sunrise() : Returns the time of sunrise for a given day / location

date_sunset() : Returns the time of sunset for a given day / location

date() Formats a local time/date getdate() : Returns an array that contains date and time information for a Unix timestamp

gettimeofday() : Returns an array that contains current time information

gmdate() : Formats a GMT/UTC date/time

gmmktime() : Returns the Unix timestamp for a GMT date

gmstrftime() : Formats a GMT/UTC time/date according to locale settings

idate() : Formats a local time/date as integer

localtime() : Returns an array that contains the time components of a Unix timestamp

microtime() : Returns the microseconds for the current time

mktime() : Returns the Unix timestamp for a date

strftime() : Formats a local time/date according to locale settings

strptime() : Parses a time/date generated with strftime()

strtotime() : Parses an English textual date or time into a Unix timestamp

time() : Returns the current time as a Unix timestamp

Posted in Functions, PHP | Leave a Comment »

PHP MySQL Functions

Posted by Ramkumar on February 13, 2009

mysql_affected_rows() : Returns the number of affected rows in the previous MySQL operation

mysql_change_user() : Deprecated. Changes the user of the current MySQL connection

mysql_client_encoding() : Returns the name of the character set for the current connection

mysql_close() : Closes a non-persistent MySQL connection

mysql_connect() : Opens a non-persistent MySQL connection

mysql_create_db() : Deprecated. Creates a new MySQL database. Use mysql_query() instead

mysql_data_seek() : Moves the record pointer

mysql_db_name() : Returns a database name from a call to mysql_list_dbs()

mysql_db_query() : Deprecated. Sends a MySQL query. Use mysql_select_db() and mysql_query() instead

mysql_drop_db() : Deprecated. Deletes a MySQL database. Use mysql_query() instead

mysql_errno() : Returns the error number of the last MySQL operation

mysql_error() : Returns the error description of the last MySQL operation

mysql_escape_string() : Deprecated. Escapes a string for use in a mysql_query. Use mysql_real_escape_string() instead

mysql_fetch_array() : Returns a row from a recordset as an associative array and/or a numeric array

mysql_fetch_assoc() : Returns a row from a recordset as an associative array

mysql_fetch_field() : Returns column info from a recordset as an object

mysql_fetch_lengths() : Returns the length of the contents of each field in a result row

mysql_fetch_object() : Returns a row from a recordset as an object

mysql_fetch_row() : Returns a row from a recordset as a numeric array

mysql_field_flags() : Returns the flags associated with a field in a recordset

mysql_field_len() : Returns the maximum length of a field in a recordset

mysql_field_name() : Returns the name of a field in a recordset

mysql_field_seek() : Moves the result pointer to a specified field

mysql_field_table() : Returns the name of the table the specified field is in

mysql_field_type() : Returns the type of a field in a recordset

mysql_free_result() : Free result memory

mysql_get_client_info() : Returns MySQL client info

mysql_get_host_info() : Returns MySQL host info

mysql_get_proto_info() : Returns MySQL protocol info

mysql_get_server_info() : Returns MySQL server info

mysql_info() : Returns information about the last query

mysql_insert_id() : Returns the AUTO_INCREMENT ID generated from the previous INSERT operation

mysql_list_dbs() : Lists available databases on a MySQL server

mysql_list_fields() : Deprecated. Lists MySQL table fields. Use mysql_query() instead

mysql_list_processes() : Lists MySQL processes

mysql_list_tables() : Deprecated. Lists tables in a MySQL database. Use mysql_query() instead

mysql_num_fields() : Returns the number of fields in a recordset

mysql_num_rows() : Returns the number of rows in a recordset

mysql_pconnect() : Opens a persistent MySQL connection

mysql_ping() : Pings a server connection or reconnects if there is no connection

mysql_query() : Executes a query on a MySQL database

mysql_real_escape_string() : Escapes a string for use in SQL statements

mysql_result() : Returns the value of a field in a recordset

mysql_select_db() : Sets the active MySQL database

mysql_stat() : Returns the current system status of the MySQL server

mysql_tablename() : Deprecated. Returns the table name of field. Use mysql_query() instead

mysql_thread_id() : Returns the current thread ID

mysql_unbuffered_query() : Executes a query on a MySQL database (without fetching / buffering the result

Posted in Functions, PHP | 1 Comment »

Zip File Functions in php

Posted by Ramkumar on February 13, 2009

zip_close() :  Closes a ZIP file

zip_entry_close() :Closes an entry in the ZIP file

zip_entry_compressedsize() : Returns the compressed size of an entry in the ZIP file

zip_entry_compressionmethod() : Returns the compression method of an entry in the ZIP file

zip_entry_filesize() : Returns the actual file size of an entry in the ZIP file

zip_entry_name() : Returns the name of an entry in the ZIP file

zip_entry_open() : Opens an entry in the ZIP file for reading

zip_entry_read() : Reads from an open entry in the ZIP file

zip_open() : Opens a ZIP file

zip_read() :  Reads the next entry in a ZIP file

Posted in Functions, PHP | Leave a Comment »

String Function in php

Posted by Ramkumar on February 13, 2009

addcslashes() : Returns a string with backslashes in front of the specified characters

addslashes() : Returns a string with backslashes in front of predefined characters

bin2hex() : Converts a string of ASCII characters to hexadecimal values

chop() : Alias of rtrim()

chr() : Returns a character from a specified ASCII value

chunk_split() : Splits a string into a series of smaller parts

convert_cyr_string() : Converts a string from one Cyrillic character-set to another

convert_uudecode() : Decodes a uuencoded string

convert_uuencode() : Encodes a string using the uuencode algorithm

count_chars() : Returns how many times an ASCII character occurs within a string and returns the information

crc32() : Calculates a 32-bit CRC for a string

crypt() : One-way string encryption (hashing)

echo() : Outputs strings

explode() : Breaks a string into an array

fprintf() : Writes a formatted string to a specified output stream

get_html_translation_table() : Returns the translation table used by htmlspecialchars() and htmlentities()

hebrev() : Converts Hebrew text to visual text

hebrevc() : Converts Hebrew text to visual text and new lines (\n) into <br />

html_entity_decode() : Converts HTML entities to characters

htmlentities() : Converts characters to HTML entities

htmlspecialchars_decode() : Converts some predefined HTML entities to characters

htmlspecialchars() : Converts some predefined characters to HTML entities

implode() : Returns a string from the elements of an array

join() : Alias of implode()

levenshtein() : Returns the Levenshtein distance between two strings

localeconv() :Returns locale numeric and monetary formatting information

ltrim() :  Strips whitespace from the left side of a string

md5() : Calculates the MD5 hash of a string

md5_file() : Calculates the MD5 hash of a file

metaphone() : Calculates the metaphone key of a string

money_format() : Returns a string formatted as a currency string

nl_langinfo() : Returns specific local information

nl2br() : Inserts HTML line breaks in front of each newline in a string

number_format() : Formats a number with grouped thousands

ord() : Returns the ASCII value of the first character of a string

parse_str() : Parses a query string into variables

print() : Outputs a string

printf() : Outputs a formatted string

quoted_printable_decode() : Decodes a quoted-printable string

quotemeta() : Quotes meta characters

rtrim() :Strips whitespace from the right side of a string

setlocale() : Sets locale information

sha1() : Calculates the SHA-1 hash of a string

sha1_file() : Calculates the SHA-1 hash of a file

similar_text() : Calculates the similarity between two strings

soundex() : Calculates the soundex key of a string

sprintf() : Writes a formatted string to a variable

sscanf() : Parses input from a string according to a format

str_ireplace() : Replaces some characters in a string (case-insensitive)

str_pad() : Pads a string to a new length

str_repeat() : Repeats a string a specified number of times

str_replace() : Replaces some characters in a string (case-sensitive)

str_rot13() : Performs the ROT13 encoding on a string

str_shuffle() : Randomly shuffles all characters in a string

str_split() : Splits a string into an array

str_word_count() : Count the number of words in a string

strcasecmp() : Compares two strings (case-insensitive)

strchr() : Finds the first occurrence of a string inside another string (alias of strstr())

strcmp() : Compares two strings (case-sensitive)

strcoll() : Locale based string comparison

strcspn() : Returns the number of characters found in a string before any part of some specified characters are found

strip_tags() : Strips HTML and PHP tags from a string

stripcslashes() : Unquotes a string quoted with addcslashes()

stripslashes() : Unquotes a string quoted with addslashes()

stripos() : Returns the position of the first occurrence of a string inside another string (case-insensitive)

stristr() : Finds the first occurrence of a string inside another string (case-insensitive)

strlen() : Returns the length of a string

strnatcasecmp() : Compares two strings using a “natural order” algorithm (case-insensitive)

strnatcmp() : Compares two strings using a “natural order” algorithm (case-sensitive)

strncasecmp() : String comparison of the first n characters (case-insensitive)

strncmp() :String comparison of the first n characters (case-sensitive)

strpbrk() : Searches a string for any of a set of characters

strpos() : Returns the position of the first occurrence of a string inside another string (case-sensitive)

strrchr() : Finds the last occurrence of a string inside another string

strrev() : Reverses a string

strripos() : Finds the position of the last occurrence of a string inside another string (case-insensitive)

strrpos() : Finds the position of the last occurrence of a string inside another string (case-sensitive)

strspn() : Returns the number of characters found in a string that contains only characters from a specified charlist

strstr() : Finds the first occurrence of a string inside another string (case-sensitive)

strtok() : Splits a string into smaller strings

strtolower() : Converts a string to lowercase letters

strtoupper() : Converts a string to uppercase letters

strtr() : Translates certain characters in a string

substr() : Returns a part of a string

substr_compare() : Compares two strings from a specified start position (binary safe and optionally case-sensitive)

substr_count() : Counts the number of times a substring occurs in a string

substr_replace() : Replaces a part of a string with another string

trim() : Strips whitespace from both sides of a string

ucfirst() :Converts the first character of a string to uppercase

ucwords() : Converts the first character of each word in a string to uppercase

vfprintf() : Writes a formatted string to a specified output stream

vprintf() : Outputs a formatted string

vsprintf() : Writes a formatted string to a variable

wordwrap() :Wraps a string to a given number of characters

Posted in Functions, PHP | Leave a Comment »

PHP Superglobals

Posted by Ramkumar on February 12, 2009

PHP Superglobals : The PHP Superglobals are a handful of arrays that provide to a PHP script global access to data originating externally. Whereas PHP scripts contain variables that are local to that script and functions may have variables that are only accessible within that function, the PHP Superglobals represent data coming from URLs, HTML forms, cookies, sessions, and the Web server itself. $HTTP_GET_VARS, $HTTP_POST_VARS, etc., served these same purposes but the PHP superglobal variables are better in that they can also be accessed within any functions (i.e., they have global scope)

* $_GET The $_GET Superglobal represents data sent to the PHP script in a URL. This applies both to directly accessed URLs (e.g., http://www.example.com/page.php?id=2) and form submissions that use the GET method.

* $_POST The $_POST Superglobal represents data sent to the PHP script via HTTP POST. This is normally a form with a method of POST.

* $_COOKIE The $_COOKIE Superglobal represents data available to a PHP script via HTTP cookies.

* $_REQUEST The $_REQUEST Superglobal is a combination of $_GET, $_POST, and $_COOKIE.

* $_SESSION The $_SESSION Superglobal represents data available to a PHP script that has previously been stored in a session.

* $_SERVER The $_SERVER Superglobal represents data available to a PHP script from the Web server itself. Common uses of $_SERVER is to refer to the current PHP script ($_SERVER['PHP_SELF']), the path on the server to that script, the host name, and so on. (The image at right shows some sample $_SERVER values, which can be easily viewed in NuSphere’s PhpED’s Globals pane.)

* $_ENV The $_ENV Superglobal represents data available to a PHP script from the environment in which PHP is running.

* $_FILES The $_FILES Superglobal represents data available to a PHP script from HTTP POST file uploads. Using $_FILES is the currently preferred way to handle uploaded files in PHP.

Another PHP Superglobal, called $GLOBALS, stores every variable with global scope, which includes the above. Unlike the other Superglobals, $GLOBALS has been around since PHP 3.

Note : One key aspect of Web application security is referring to variables with precision, which is why relying upon register_globals is bad. For the same reason, one should not use $_REQUEST as it is less exact, and therefore less secure, than explicitly referring to $_GET, $_POST, or $_COOKIE. Furthermore, the order in which the GET, POST, and COOKIE data is loaded into the $_REQUEST array is dictated by PHP’s variables_orders configuration, so the same reference to $_REQUEST in a PHP script could behave differently on different servers.

Posted in Introduction, PHP | Leave a Comment »

Preg in PHP

Posted by Ramkumar on February 12, 2009

Preg_Grep PHP Function

The PHP function, preg_grep, is used to search an array for specific patterns and then return a new array based on that filtering. There are two ways to return the results. You can return them as is, or you can invert them (instead of only returning what matches, it would only return what does not match.) It is phrased as: preg_grep ( search_pattern, $your_array, optional_inverse ) The search_pattern needs to be a regular expression. If you are unfamiliar with them this article gives you an overview of the syntax.

<?
$data = array(0, 1, 2, ‘three’, 4, 5, ’six’, 7, 8, ‘nine’, 10);
$mod1 = preg_grep(“/4|5|6/”, $data);
$mod2 = preg_grep(“/[0-9]/”, $data, PREG_GREP_INVERT);
print_r($mod1);
echo “<br>”;
print_r($mod2);
?>

This code would result in the following data:
Array ( [4] => 4 [5] => 5 )
Array ( [3] => three [6] => six [9] => nine )

First we assign our $data variable. This is a list of numbers, some in alpha form, others in numeric. The first thing we run is called $mod1. Here we are searching for anything that contains 4, 5, or 6. When our result is printed below we only get 4 and 5, because 6 was written as ’six’ so it did not match our search.

Next we run $mod2, which is searching for anything that contains a numeric character. But this time we include PREG_GREP_INVERT. This will invert our data, so instead of outputting numbers, it outputs all of our entries that where not numeric (three, six and nine).

Preg_Match PHP Function

The Preg_Match PHP function is used to search a string, and return a 1 or 0. If the search was successful a 1 will be returned, and if it was not found a 0 will be returned. Although other variables can be added, it is most simply phrased as: preg_match(search_pattern, your_string). The search_pattern needs to be a regular expression. If you are unfamiliar with them this article gives you an overview of the syntax.

<?
$data = “I had a box of cerial for breakfast today, and then I drank some juice.”;
if (preg_match(“/juice/”, $data))
{
echo “You had juice.<br>”;
}
else
{
echo “You had did not have juice.<br>”;
}
if (preg_match(“/eggs/”, $data))
{
echo “You had eggs.<br>”;
}
else
{
echo “You had did not have eggs.<br>”;
}
?>

The code above uses preg_match to check for a key word (first juice then egg) and replies based on whether it is true (1) or false (0). Because it returns these two values it is most often used in a conditional statement.

Preg_Match_All PHP Function
Preg_Match_All is used to search a string for specific patterns and stores the results in an array. Unlike preg_match which stops searching after it finds a match, preg_match_all searches the entire string and records all matches. It is phrased as: preg_match_all (pattern, string, $array, optional_ordering, optional_offset)

<? $data = “The party will start at 10:30 pm and run untill 12:30 am”;
preg_match_all(‘/(\d+:\d+)\s*(am|pm)/’, $data, $match, PREG_PATTERN_ORDER);
echo “Full: <br>”;
print_r($match[0]);
echo “<p>Raw: <br>”;
print_r($match[1]);
echo “<p>Tags: <br>”;
print_r($match[2]);
?>

In our first example we use PREG_PATTERN_ORDER. We are searching for 2 things; one is the time, the other is it’s am/pm tag. Our results are outputted to $match, as an array where $match[0] contains all matches, $match[1] contains all data matching our first sub-serach (the time) and $match[2] contains all data matching our second sub-search (am/pm).

<? $data = “The party will start at 10:30 pm and run untill 12:30 am”;
preg_match_all(‘/(\d+:\d+)\s*(am|pm)/’, $data, $match, PREG_SET_ORDER);
echo “First: <br>”;
echo $match[0][0] . ” , ” . $match[0][1] . ” , “. $match [0][2] .”<br>”;
echo “Second: <br>”;
echo $match[1][0] . ” , ” . $match[1][1] . ” , “. $match [1][2] .”<br>”;
?>

In our second example we use PREG_SET_ORDER. This puts each full result into an array. The first result is $match[0], with $match[0][0] being the full match, $match[0][1] being the first sub-match and $match[0][2] being the second sub-match.

Preg_Replace PHP Function

The preg_replace function is used to do a find-and-replace on a string or an array. We can give it one thing to find and replace (for example it seeks out the word ‘him’ and changes it to ‘her’) or we can give it a full list of things (an array) to search for, each with a corresponding replacement. It is phrased as preg_replace ( search_for, replace_with, your_data , optional_limit, optional_count ) The limit will default to -1 which is no limit. Remember your_data can be a string or an array.

<?
$data = “The cat likes to sit on the fence. He also likes to climb the tree.”;

$find =”/the/”;
$replace =”a”;

//1. replace single word
Echo “$data <br>”;
Echo preg_replace ($find, $replace, $data);

//create arrays
$find2 = array (‘/the/’, ‘/cat/’);
$replace2 = array (‘a’, ‘dog’);

//2. replace with array values
Echo preg_replace ($find2, $replace2, $data);

//3. Replace just once
Echo preg_replace ($find2, $replace2, $data, 1);

//4. Keep a count of replacements
$count = 0;
Echo preg_replace ($find2, $replace2, $data, -1, $count);
Echo “<br>You have made $count replacements”;

?>

In our first example we simply replace ‘the’ with ‘a’. As you can see these are cAse seNsiTIvE. Then we set up an array, so in our second example we are replacing both the words ‘the’ and ‘cat’. In our third example, we set the limit to 1, so each word is only replaced one time. Finally in our 4th example, we keep count of how many replacements we have made.

Preg_Split PHP Function

The function Preg_Spilit is used to take a string, and put it into an array. The string is broken up into different values in the array based upon your input. It is phrased as preg_split ( split_pattern, your_data, optional_limit, optional_flags )

<?php
$str = ‘I like goats. You like cats. He likes dogs.’;
$chars = preg_split(‘//’, $str);
print_r($chars);
echo “<p>”;
$words= preg_split(‘/ /’, $str);
print_r($words);
echo “<p>”;
$sentances= preg_split(‘/\./’, $str, -1 , PREG_SPLIT_NO_EMPTY);
print_r($sentances);
?>

In the code above we preform three splits. In our first, we split the data by each character. In the second, we split it with a blank space, thus giving each word (and not each letter) an array entry. And in our third example we use a ‘.’ period to split the data, therefor giving each sentence it’s own array entry.

Because in our last example we use a ‘.’ period to split, a new entry is started after our final period, so we add the flag PREG_SPLIT_NO_EMPTY so that no empty results are returned. Other available flags are PREG_SPLIT_DELIM_CAPTURE which also captures the character you are splitting by (our “.” for example) and PREG_SPLIT_OFFSET_CAPTURE which captures the offset in characters where the split has occurred.

Posted in Functions, PHP | Tagged: , | Leave a Comment »

Working with xml on php

Posted by Ramkumar on February 12, 2009

Test.xml

<?xml version=”1.0″?>

<news>

<story>

<headline> Godzilla Attacks LA! </headline>
<description>Equipped with a Japanese Mind-control device, the giant monster has attacked important harbours along the California coast. President to take action. </description>

</story>

<story>

<headline> Bigfoot Spotted at M.I.T. Dining Area </headline>
<description>The beast was seen ordering a Snapple in the dining area on Tuesday. In a related story, Kirupa Chinnathambi, an MIT engineering student has been reported missing. </description>

</story>

<story>

<headline> London Angel Saves England </headline>
<description>The “London Angel” known only as “Kit” has saved the U.K. yet again. Reports have stated that she destroyed every single Churchill bobble-head dog in the country. A great heartfilled thank you goes out to her. </description>

</story>

<story>

<headline> Six-eyed Man to be Wed to an Eight-armed Woman </headline>
<description>Uhhhmmm… No comment really… just a little creepy to see them together… </description>

</story>

<story>

<headline> Ahmed’s Birthday Extravaganza! </headline>
<description>The gifted youngster’s birthday party should be a blast. He is turning thirteen and has requested a large cake, ice cream, and a petting zoo complete with pony rides. </description>

</story>

</news>

Sample.php
<?php

$xml_file = “text.xml”;

$xml_headline_key = “*NEWS*STORY*HEADLINE”;
$xml_description_key = “*NEWS*STORY*DESCRIPTION”;

$story_array = array();

$counter = 0;
class xml_story{
var $headline, $description;
}

function startTag($parser, $data){
global $current_tag;
$current_tag .= “*$data”;
}

function endTag($parser, $data){
global $current_tag;
$tag_key = strrpos($current_tag, ‘*’);
$current_tag = substr($current_tag, 0, $tag_key);
}

function contents($parser, $data){
global $current_tag, $xml_headline_key, $xml_description_key, $counter, $story_array;
switch($current_tag){
case $xml_headline_key:
$story_array[$counter] = new xml_story();
$story_array[$counter]->headline = $data;
break;
case $xml_description_key:
$story_array[$counter]->description = $data;
$counter++;
break;
}
}

$xml_parser = xml_parser_create();

xml_set_element_handler($xml_parser, “startTag”, “endTag”);

xml_set_character_data_handler($xml_parser, “contents”);

$fp = fopen($xml_file, “r”) or die(“Could not open file”);

$data = fread($fp, filesize($xml_file)) or die(“Could not read file”);

if(!(xml_parse($xml_parser, $data, feof($fp)))){
die(“Error on line ” . xml_get_current_line_number($xml_parser));
}

xml_parser_free($xml_parser);

fclose($fp);

?>

<html>
<head>
<title>CNT HEADLINE NEWS</title>
</head>
<body bgcolor=”#FFFFFF”>
<?php
for($x=0;$x<count($story_array);$x++){
echo “\t<h2>” . $story_array[$x]->headline . “</h2>\n”;
echo “\t\t\n”;
echo “\t<i>” . $story_array[$x]->description . “</i>\n”;
}
?>

</body>
</html>

Explaination;

This project needs a bit more setup than before. In addition to our 3 main functions:

-A function to handle the start tags
-A function to handle the data between the tags
-A function to handle the end tags

We need a few more things:

-Our XML tag keys
-An array to store information
-A counter
-A class

Thats what we have in the following explanations:

$xml_headline_key = “*NEWS*STORY*HEADLINE”;
$xml_description_key = “*NEWS*STORY*DESCRIPTION”;

These are our tag keys. They are the different levels of hierarchical tags in our XML file. Because we don’t actually have any information in the “news” or the “story” tags we don’t have to include them. Our main focus is on the “headline” and the “description” tags. We will use these tags later on in the script.

$story_array = array();
$counter = 0;

Here we are simply initializing our array and our counter for later use.

Now we come up upon our 3 major functions for parsing and formating our data. Same as before they are the “startTag”, “endTag”, and “contents” functions. Ultimately they do the same things as before. They perform their designated actions when they are called on by the parser. The only change in this file is that the actions are a bit more complex. In this tutorial we’ll go through each function fully before moving on to the next. We’ll start with “startTag”:

function startTag($parser, $data){
global $current_tag;
$current_tag .= “*$data”;
}

When the script hits a start tag it will add the tag that it is currently reading to the string $current_tag. There is a “global” in front of our variable because we will be using the variable in all three of our functions and in order to use it the way we want, we need to declare it as a global variable instead of a local variable.

function endTag($parser, $data){
global $current_tag;
$tag_key = strrpos($current_tag, ‘*’);
$current_tag = substr($current_tag, 0, $tag_key);
}

Again we delcare $current_tag as global so we can use it just like the “startTag”. The variable $tag_key is used to mark the last occurence of an asterix (*) in the string $current_tag. Then the string $current_tag is cut back by one XML tag. The purpose of this function is to take a step back just as the purpose of “startTag” is to take a step forward.

function contents($parser, $data){
global $current_tag, $xml_headline_key, $xml_description_key, $counter, $story_array;
switch($current_tag){
case $xml_headline_key:
$story_array[$counter] = new xml_story();
$story_array[$counter]->headline = $data;
break;
case $xml_description_key:
$story_array[$counter]->description = $data;
$counter++;
break;
}
}

Our first line of this functions declares all of our variables: $current_tag, $xml_headline_key, $xml_description_key, etc… The next line begins our switch statement. Switch() is basically another method for if() statements. For more on switch() in PHP visit php.net. What this switch statement is doing is comparing the variable $current_tag to the variables $xml_headline_key and $xml_description_key and if it finds a match it performs the scripted actions.

If $current_tag matches $xml_headline_key the script defines $story_array[$counter] as a new xml_story() object. Then we assign our data to our new objects “headline” property with this line:

$story_array[$counter]->headline = $data;

Then it breaks the switch statement. If the $current_tag matches $xml_description_key it assigns the data to the objects “description” property and adds 1 to our $counter variable, then breaks out of the switch statement.

Just to clarify, I prefer to use the object method to keep track of my data a little easier. This is just what works for me. Other people may have other methods that work better for them. Its all about you’re own personal preferences. Next up are the XML functions, which are exactly the same as in the {Easy} tutorial.

XML functions
For the XML functions, we need to:

-Create the parser
-Set the start and end tag handlers
-Set the data handler
-Open the XML file
-Read the XML file
-Parse the XML data
-Destroy the parser
-Close the XML file

Creating the parser is easy:

$xml_parser = xml_parser_create();

Setting the start tag, end tag, and data handlers are pretty easy as well:

xml_set_element_handler($xml_parser, “startTag”, “endTag”);

xml_set_character_data_handler($xml_parser, “contents”);

The first argument for both of these functions is always the name of the parser we created in the previous step. The next arguments are the functions we created a little earlier. Next up is opening and reading the XML file:

$fp = fopen($file, “r”);

$data = fread($fp, 80000);

These are basic file handling functions that you should be familiar with by now. If you need to learn more or just refresh your memory you can check out the great tutorials on php.net.

The following if statement does two things: 1) it parses through the XML data from the XML file, and 2) if the parse fails it outputs an error message complete with line number.

if(!(xml_parse($xml_parser, $data, feof($fp)))){
die(“Error on line ” . xml_get_current_line_number($xml_parser));
}

Again the first argument of the function is our parser. The second argument is the data to be parsed, in this case the variable $data. The third argument tells the function to keep parsing until it reaches the end of the file.

The next two lines just wrap up the script. The first one frees up the memory used by the server to create the parser and the second closes the XML file. Both of these lines are very important so do not forget to include them in your script. Failure to do so could result in problems with your server.

xml_parser_free($xml_parser);

fclose($fp);

Wrapping it up
Well thats all fine and good. Now we have our XML parsed and the data is stored into our objects. All we have left to do is format it. We can pretty much do whatever we want to do with it now. I prefer to keep this simple for the example, so the code is just a simple for() loop that outputs our information into headers.

<html>
<head>
<title>CNT HEADLINE NEWS</title>
</head>
<body bgcolor=”#FFFFFF”>
<?
// A simple for loop that outputs our final data.
for($x=0;$x<count($story_array);$x++){
echo “\t<h2>” . $story_array[$x]->headline . “</h2>\n”;
echo “\t\t\n”;
echo “\t<i>” . $story_array[$x]->description . “</i>\n”;
}
?>

</body>
</html>

Source : http://www.kirupa.com/web/xml_php_parse_intermediate.htm

Posted in PHP | Tagged: , | Leave a Comment »

Differences Between PHP 4 and 5

Posted by Ramkumar on January 29, 2009

Differences Between PHP 4 and 5

Language Features

  • PHP 5 allows limited type hinting. This allows you to specify that the parameter

to a function or class method can only be of a specific class (or one of its

subclasses), or an array. However, you may not specify any other scalar types.

  • The foreach construct now supports by-reference declaration of the value element.
  • A number of new functions, particularly for string and arraymanipulation, has

also been added to the core platform.

Objects

  • For all intents and purposes, all objects in PHP 5 are passed by reference. This

means that assigning an object to a variable will not create a copy of the former,

but simply creates another reference to it.

  • Constants, aswell as staticmethods and properties, can nowbe definedwithin

the scope of a class.

  • Class methods and properties now feature visibility, and can be declared as

public, private or protected. Classes and methods can also be declared as

final to prevent further inheritance.

  • Since all objects are assigned by reference, you now need a specialized mechanism

to copy objects. This is provided by the clone construct and the __clone()

magic method.

  • PHP 5 features unified constructors and destructors-all constructors should

now be named __construct(), and the new __destruct() magic method has

been added for object destruction.

  • With the addition of interfaces and abstract classes, PHP developers now have

far greater control over how they implement their object-oriented code. Interfaces

can be used to define common APIs, while abstract classes provide

models for class implementations that follow a specific blueprint.

  • Class definitions can now be loaded on demand by using the __autoload()

function.

MagicMethods

A multitude of new “magic” methods has been introduced in PHP 5:

  • __get() and __set() are called when accessing or assigning an undefined object

property, while __call() is executed when calling a non-existent method

of a class.

  • __isset() is called when passing an undefined property to the isset() construct.
  • __unset() is called when passing an undefined property to unset().
  • __toString() is called when trying to directly echo or print() an object.
  • __set_state() is inserted dynamically by var_export() to allow for reinitialization

on execution of var_export()’s output.

Selected New Extensions

  • SimpleXML allows easy access to XML data using object and array notation.
  • PHP 5 also introduces a DOMXML, DOMXSL and Sablotron replacement in

the formof the libxml2-based DOM and XSL extensions.

  • The PHP Data Objects (PDO) extension provides a unified database access extension

that allows access to many different types of database systems by using

a common interface. PDO is not an abstraction layer-except for prepared

queries, it does nothing to abstract the actual database code (SQL), itself.

  • The hash extension is a new replacement for the GPLed libmhash; it was added

to the PHP core starting with version 5.1.2. It can produce hashes using many

algorithms, including the familiarMD5and SHA1, aswell as some more secure

(albeit slower) algorithms, such as snefru.

  • The Standard PHP Library (SPL) provides numerous interfaces that enhance

the way classes interact with the PHP language, including the new Iterator

interfaces.

  • The new Reflection extension allows for runtime introspection of executing

PHP code.

ErrorManagement

  • Classes now support exceptions; the new set_exception_handler() function

allows you to define a script-wide exception handler.

  • The E_STRICT error reporting level has been added to the language to emit notices

when legacy or deprecated code is encountered.

Posted in Interview Questions, Introduction, PHP | Tagged: , | 1 Comment »

Class in PHP

Posted by Ramkumar on January 25, 2009

  1. Creating Our First Object
  2. Class Variables and Visibility
  3. Constructor Method
  4. Using Arrays to Speed Up Coding
  5. Method Interaction
  6. Integrating OO PHP with MySQL
  7. Introducing Inheritance
  8. Parting Words
  9. Now let’s get started!

Creating Our First Object

not surprisingly, object oriented programming is focused around objects. While the idea of objects may be foreign to you in coding terms, understanding what objects are and why we use them shouldn’t take long. In short, our non-programming world is comprised of objects. Computers, fish, clouds, people, and cars are all objects. Objects have properties like color, size, name, and speed. Objects can also be comprised of other objects: cars have doors; doors have handles; handles have plastic levers; so on and so forth. Objects are everywhere around us. For this reason, many programmers find object oriented programming relatively easy to understand.

So how do objects translate into code? If we were building a website about users, we would create one or many user objects. Objects are created using classes. Classes are groups of related variables and functions. Variables hold our object’s properties like color, size, and speed. Functions perform actions like set variable values or open files. In this example, we could create user objects with a User class. You can think of the User class as a template for any user objects.

Creating an object is called instantiation (creating an instance). Let’s instantiate a user objects and codes the corresponding User class:

/* create new object */
$ram = new User;
/* class to create objects with */
class User {
}

Note: As these tutorial progresses, code will be removed so that you don’t get lost and can focus on the task at hand. Feel free to keep or add back code from previous examples.

Right now this user can’t do anything and doesn’t have any attributes. Within classes, we use methods (aka functions) and variables to give our objects functionality and properties. Let’s redo our first example so that our users can have a name:

/* create a new object */
$ram = new User;
/* call object methods */
$ram->setName( ‘ram’ );
echo $ram->getName().’<br />’;
class User {
private $name;
function setName( $val ) {
$this->name = $val;
return;

}
function getName() {
return $this->name;
}}

As you can see, methods are declared using function [methodName] format, as is standard in PHP. This simple example shows us how we can apply a name to the object, then access the name. Continue on to learn about how we handle variables and methods within classes.

Class Variables and Visibility

Within classes, we first define our variables. In this case, our first variable is $name. A handy feature of PHP5 (not PHP4) is increased visibility control. Our $name variable currently has a visibility of private. Private visibility means that the variable can only be accessed via the methods inside the class (like setName and getName). If we set the variable visibility to public, our variable could be accessed externally (without the methods). The final visibility setting for a variable is protected, which means that variable access is limited to parent and inherited classes, which we will discuss more later.

In PHP4, public is the only visibility option and public variables are declared using var instead of public. Let’s take a look at how variable visibility works by adding a $location variable and setting it to public visibility:

/* instantiate object */
$ram = new User;
/* access private variables via methods, then try without methods */
$ram->setName( ram’ );
echo $ram->getName().’<br />’;  // ram
echo $ram->name.’<br />’;                           // breaks our code
/* access public variables without methods will work */
$ram->location = ‘MIT’;
echo $ram->location.’<br />’;       // MIT
class User {
private $name;                     // must be accessed with methods.
// not available in PHP4
public $location;  // can be accessed without methods
// var $location; in PHP4

function setName( $val ) {
$this->name = $val;
return;
}
function getName() {
return $this->name;
}}

So which variable visibility should you choose? The answer is that it depends. In general, you should be fine using private. Private is especially useful because it supports encapsulation – the ability to hide data and only make it accessible through a given interface. In OOP, an interface represents the functionality given to a particular object.

Just as we set a variable’s visibility, we can also set visibility for methods. By default, if we don’t set the visibility of our methods, they will be set to public. For the sake of time, we will not dig into examples with different method visibility. Continue on to learn about an important and useful method, the constructor.

Note about $this: Within methods, we refer to class variables and other methods using $this->. This can be seen within the setName and getName methods. $this is a default variable created upon instantiation and enables an object to reference itself.

Note about naming conventions: While set[PropertyName] and

get[PropertyName] are popular method names because they are easily understood, they are not required. You can name these methods whatever you want.

Constructor Method

Now is a good time to look at the constructor method. The constructor is a method that will automatically be run when an object is instantiated. In PHP5, we have methods called “Magic Methods” (i.e. __construct, __destruct, and a few others) which begin with two underscores. In PHP4, the constructor method would be given the same name as the class itself. So in PHP4, if we have a class named User, our constructor method would also be named User (not __construct). Remember, you do not need to call the constructor method explicitly because it will be automatically run when an instance of that class is created. Here’s a constructor in action:

$ram = new User;
echo $ram->getJob().’<br />’; // Engineer
class User {
private $job;
function __construct() {     // function User() in PHP4
$this->job = ‘Engineer’;
}
/* job methods */
function getJob() {
return $this->job;
}}

Now you might be starting to see one of the benefits of OOP – much of the code lies in the background. We could include files containing our classes to hide the heavy duty code even more. Because the naming conventions of classes and methods are fairly self explanatory, we won’t need to constantly look back at our included files. Continue reading to find out how we can use arrays to speed up our process.

Using Arrays to Speed Up Coding

Right now, it’s tedious to set each property using a set method – there must be an easier way. That’s where associative arrays combined with our constructor come in handy. Let’s create our user object and give it several properties upon instantiation:

$attribs = array(
‘name’                    => ‘ram,
‘job’                        => ‘Engineer’,
’school’  => ‘MIT’,
‘homeTown’          => ‘Spanish Fort’,
‘homeState’           => ‘Alabama’
);
$ram = new User( $attribs );
echo ‘Name: ‘.$ram->getName().’<br />’;                   // ram
echo ‘Job: ‘.$ram->getJob().’<br />’;                           // Engineer
echo ‘School: ‘.$ram->getSchool().’<br />’;                               // MIT
echo ‘Home Town: ‘.$ram->getHomeTown().’<br />’;              // Spanish Fort
echo ‘Home State: ‘.$ram->getHomeState().’<br />’;               // Alabama

class User {
private $name;
private $job;
private $school;
private $homeTown;
private $homeState;
function __construct( $attribs ) {
$this->name                          = $attribs['name'];
$this->job                              = $attribs['job'];
$this->school                        = $attribs['school'];
$this->homeTown                                = $attribs['homeTown'];
$this->homeState                = $attribs['homeState'];
}
/* name methods */

function setName( $val ) {
$this->name = $val;
return;
}
function getName() {
return $this->name;
}
/* job methods */
function setJob( $val ) {
$this->job = $val;
return;
}
function getJob() {
return $this->job;
}
/* school methods */
function setSchool( $val ) {
$this->school = $val;
return;
}
function getSchool() {
return $this->school;
}
/* home town methods */
function setHomeTown( $val ) {
$this->homeTown = $val;
}
function getHomeTown() {
return $this->homeTown;
}
/* home state methods */
function setHomeState( $val ) {
$this->homeState = $val;
}
function getHomeState() {
return $this->homeState;
}}

I have kept the set methods in case we want to change the properties, but now the properties are established up front via __construct. That is, we passed our $attribs array to the object on instantiation, which in turn passed $attribs to the constructor automatically. The advantage to using associative arrays for this purpose is that we don’t need to explicitly set all of our variables with the methods. This is extremely handy when integrating PHP with MySQL data, which we will cover soon. But first, we need to learn a little bit about method interaction and object grouping.

Method Interaction

At this point, our methods do not interact. Let’s add a little functionality to our example by converting full state names to the appropriate abbreviations.

$attribs = array(
‘name’                    => ‘ram’,
‘homeState’           => ‘Alabama’
);
$ram = new User( $attribs );
echo ‘Name: ‘.$ram->getName().’<br />’;                                 // ram
echo ‘Home State: ‘.$ram->getHomeState().’<br />’;                               // Alabama
echo ‘State Abbr.: ‘.$ram->getHomeStateAbbr().’<br />’;       // AL
class User {
private $name;
private $homeState;
function __construct( $attribs ) {
$this->name                          = $attribs['name'];
$this->homeState                = $attribs['homeState'];
}
/* name methods */
function setName( $val ) {
$this->name = $val;
return;
}
function getName() {
return $this->name;
}
/* home state methods */
function setHomeState( $val ) {
$this->homeState = $val;
}
function getHomeState() {
return $this->homeState;
}
function getHomeStateAbbr() {
$abbr = States::$ABBRS[$this->getHomeState()];
if( $abbr ) {
return $abbr;
}
else {
return ‘Unknown’;
}
}}
class States {
/* ideally this would be held in a database */
static $ABBRS = array (
‘Alabama’               => ‘AL’,
‘Michigan’              => ‘MI’,
‘New York’             => ‘NY’
);}

In this example, we used a full state name to get its corresponding abbreviation. We did this using a class with a static variable. Static variables generally do not change and can be accessed without methods. These variables act more as reference and can be useful for things like your database connection settings and other site wide variables. Static variables are usually named with all capital letters.

Next, we will learn to integrate our object oriented PHP with MySQL.

Integrating OO PHP with MySQL

In this section, we will kill two birds with one stone. Not only will we learn how to integrate OO PHP and MySQL, but we will learn how to group objects. In this case, you will create a UsersGroup class which will contain an array of User objects. Each of those User objects will be created using a row from a MySQL query. To try this practical example, you will first need to create a Users table in a MySQL database. I am using a MySQL database named ‘ram_oop’. Use the queries below to create the table and insert the sample data.

/* Create Users table */
CREATE TABLE ‘users’ (
‘user_id’ INT NOT NULL AUTO_INCREMENT,
‘user_name’ TEXT NOT NULL,
PRIMARY KEY (‘user_id’)
);
/* Insert sample data into Users table */
INSERT INTO ‘users’
( ‘user_id’, ‘user_name’ )
VALUES
( ”, ‘ram’ ),
( ”, ‘bwh2′ );

This very simple table just has two columns: ‘user_id’ and ‘user_name’. You may wish to add your own name to this table to spice things up.

As promised, we will create a UsersGroup class. This group will contain an array of User objects, each of which is created using data from our MySQL table. All of my tables are on a database named ‘ram_oop’. If your database is not named ‘ram_oop’, you must change the database name in the Settings class shown below. Here is our UsersGroup class in action:

/* instantiate group */
$group = new UsersGroup;
/* loop through our group, echo user names */
foreach( $group->getUsers() as $user ) {
echo $user->getName().’<br />’;
}
/* User class, same as before */
class User {
private $name;
function __construct( $attribs ) {
$this->name = $attribs['name'];
}
/* name methods */
function setName( $val ) {
$this->name = $val;
return;
}
function getName() {
return $this->name;
}}
/* Contains a group of User objects */
class UsersGroup {
private $name;                                     // name of group
private $group = array();    // group of User objects
function __construct() {
/* Connect to DB using Settings */
$link = mysql_connect(
Settings::$DATABASE['host'],
Settings::$DATABASE['username'],
Settings::$DATABASE['password']
);
mysql_select_db ( Settings::$DATABASE['database'], $link );
/* Get table names from Settings class */
$tbl_users = Settings::$TABLES['tbl_users'];
/* Query */
$sql = “SELECT      user_id AS ID,
user_name AS name
FROM $tbl_users”;
$result = mysql_query( $sql ) or die(mysql_error());
/* Adds user to group with each row of data */
while( $row = mysql_fetch_array($result) ) {
$this->addUser( $row );
}
}
/*Add a user to Group
Does simple check to see if we pass an array (like $attribs)
or if we pass an object (like a User object)
*/

function addUser( $user ) {
if( is_object( $user ) ) {
array_push( $this->group, $user );
}
if( is_array( $user ) ) {
$noob = new User( $user );
array_push( $this->group, $noob );
}
return;
}
/* Returns the group (which is an array) */
function getUsers() {
return $this->group;
}}
/* Holds our site settings */
class Settings {
static $DATABASE = array(
// change these as needed ‘database’ => ‘ram_oop’, // May need to be changed ‘username’ => ‘root’, ‘password’ => ”, ‘host’ => ‘localhost’ ); static $TABLES = array( // reference to table name => actual MySQL table name ‘tbl_users’ => ‘users’ ); }
The first thing to note is that we are holding our database connection and table name information inside our Settings class, within static variables. In the event that we need to change our database name, table names, database usernames, etc. we will only do it in our Settings class (which is preferably in a separate, included file). Our User class is nothing new – it only holds the name property and still receives an array of data via __construct.

Let’s look at the code for the UsersGroup class. If you have connected to a MySQL database with PHP before, the connection should be nothing new. The only difference is that we use static variables for our connection settings. We do the same for our table names because within double quotes, our Settings class static variables cannot be parsed. That is, just using Settings::$TABLES['tbl_users'] directly in our double-quoted SQL query will cause an error.

Our SQL query produces an array of rows, which we assign to $result. Using a while loop, we go through our $result array. Each element in $result is an array of values (like id and name). Again, this should look very familiar to anyone who has used PHP to access a MySQL database. Now comes the OOP part: we then pass each row ($row) from our MySQL query to our addUser method. First, the addUser method checks if it’s being passed an array of data (like $row) or a whole User object. In this case, we are passing an array of data. Using that array of data, addUser creates a User object ($noob), then adds that user object to the group array ($group).

Note about column names: When our User object is created with array data, the constructor is looking for an array element called name. To fulfill this request, we use a SQL alias, which can be seen in $sql. If we did not alias user_name AS name the $row variable would not hold an array element called name but rather user_name. Thus, it would not correctly populate the name variable in our User object. I prefer to keep customization in my SQL rather than my PHP class methods because I am more likely to reuse PHP class methods than SQL queries. For instance, if I create a Dogs class, I would also want a getName method and constructor. Rather than modify several PHP methods to support dogs instead of users, I would rather modify one SQL query. Alternatively, you could also rename your user_name column to just name. This would maximize reusability, but may hurt your ability to understand more complex SQL queries and database designs.

You might be thinking this class is overly complex. After all, you can probably code all of this in 15 lines within a regular PHP page. So where’s the advantage? Well, look at how we use our objects:

/* instantiate group */
$group = new UsersGroup;
/* loop through our group, echo user names */
foreach( $group->getUsers as $user ) {
echo $user->getName().’<br />’;
}

Really, that’s 4 lines of code to echo out all of the users in our table. All of the database connection, querying, and real code is sitting behind the scenes. Remember, we are going to include our classes as separate files. On top of that, our classes are very reusable (aka modular). Our code is beautifully generalized and hidden from plain sight. It should also coded semantically, so it’s easy to understand. Debugging and maintenance time should be decreased significantly. In the end, we’re going to reuse this code for many sites and save tons of time and energy.

So that’s a basic user table accessed with a UsersGroup class. But what if we want some users to be Administrators and others just plain Users – how can we do that? For the answer, let’s continue on with the topic of inheritance.

Introducing Inheritance

To make this system more robust, we don’t want all of the users in our group to have the same status. Some users need to be administrators, others moderators, and others just regular users. How can we account for this in our objects? The answer is inheritance – the ability for one class to inherit methods and properties from another class. First, let’s take a look at inheritance in code:

/* ram has admin powers */
$ram = new Admin( array( ‘name’ => ‘ram’ ) );
echo $ram->getName().’<br />’;  // ram
echo $ram->getAdmin();                               // Administrator
/* Regular does not have admin powers */
$regular = new User( array( ‘name’ => ‘Regular’ ) );
$regular->getAdmin();                                        // breaks our code
/* Normal User class */
class User {
private $name;
function __construct( $attribs ) {
$this->name          = $attribs['name'];
}
function getName() {
return $this->name;
}}
/* Admin is a User, but with additional functionality */
class Admin extends User {
function getAdmin() {
return ‘Administrator’;
}}

As you can see, our Admin object has inherited the functionality of the User class using the keyword extends. On top of that, our Admin is given some additional functionality. In this case, our User class is known as the superclass. In PHP, a class may only inherit one superclass. There are more nuances to inheritance, but this tutorial will only cover the basics. In a more realistic scenario, we would code more functionality for just administrators. Perhaps something like:

/* Additional functionality for just Administrators */
class Admin extends User {
function banUser( $id ) {
/* code to ban user */
}
function unbanUser( $id ) {
/* code to unban or activate user account */
}
//…
}

For the sake of time and focus, these methods haven’t actually been coded. But this should give you some insight into how inheritance works and why it can be useful.

Continue on for a few parting words and direction.

Parting Words

By now, you should understand what objects, how to create them, and how to access their properties and methods. This tutorial is by no means all-encompassing. In fact, this is just the tip of the iceberg and was designed as such. For further reading, I suggest PHP5: Objects, Patterns, and Practice by Matt Zandstra. In addition, you could read through the OOP documentation provided at php.net.

As you begin to understand OOP more and your PHP code becomes more object oriented, you will find more code reusable and ultimately save time and energy. Pre-existing code resources such as PEAR and PHPClasses.org will become increasingly useful

Posted in Class, PHP | Tagged: , , , | Leave a Comment »