Saturday, 18 December 2010

PHP’s Supported Data Types

A datatype is the generic name assigned to any data sharing a common set of characteristics.

Common data types include Boolean, integer, float, string, and array

Scalar Data Types are used to represent a single value. Several data types fall under this category, including Boolean, integer, float, and string.

Boolean

The Boolean data type represents truth, supporting only two values: TRUE and FALSE (case insensitive). Alternatively, we can use zero to represent FALSE, and any nonzero value to represent TRUE. A few examples follow:



Integer

An integer is representative of any whole number or, in other words, a number that does not contain fractional parts. PHP supports integer values represented in base 10 (decimal), base 8 (octal), and base 16 (hexadecimal) numbering systems, although it’s likely we’ll only be concerned with the first of those systems. Several examples follow:


The maximum supported integer size is platform-dependent, although this is typically positive or negative 2^31 for PHP version 5 and earlier. PHP 6 introduced a 64-bit integer value, meaning PHP will support integer values up to positive or negative 2^63 in size.

Float

Floating-point numbers, also referred to as floats, doubles, or real numbers, allow us to specify numbers that contain fractional parts. Floats are used to represent monetary values, weights, distances, and a whole host of other representations in which a simple integer value won’t suffice. PHP’s floats can be specified in a variety of ways, several of which are demonstrated here:


String

Simply put, a string is a sequence of characters treated as a contiguous group. Strings are delimited by single or double quotes, although PHP also supports another delimitation methodology, which is introduced in the later “String Interpolation” section.
The following are all examples of valid strings:


Compound Data Types

Compound data types allow for multiple items of the same type to be aggregated under a single representative entity. The array and the object fall into this category.

Array


It’s often useful to aggregate a series of similar items together, arranging and referencing them in some specific way. This data structure, known as an array, is formally defined as an indexed collection of data values. Each member of the array index (also known as the key) references a corresponding value and can be a simple numerical reference to the value’s position in the series, or it could have some direct correlation to the value.

For example, if we were interested in creating a list of cities in Vietnam, we could use
a numerically indexed array, like so:


But what if the project required correlating the list of city to their famous sightseeing? Rather than base the keys on a numerical index, we might instead use an associative index, like this:


Object

The object is a central concept of the object-oriented programming paradigm.
Unlike the other data types contained in the PHP language, an object must be explicitly declared. This declaration of an object’s characteristics and behavior takes place within something called a class.



A class definition creates several attributes and functions pertinent to a data structure, in this case a data structure named Appliance. There is only one attribute, power, which can be modified by using the method setPower().

Converting Between Data Types Using Type Casting

Converting values from one datatype to another is known as type casting.
A variable can be evaluated once as a different type by casting it to another.
This is accomplished by placing the intended type in front of the variable to be cast.




Let’s consider several examples. Suppose we’d like to cast an integer as a double:


Output will be 13.0

Type casting a double to an integer will result in the integer value being rounded down, regardless of the decimal value. Here’s an example:


What happens if we cast a string datatype to that of an integer? Let’s find out:



Output will return to 0 (zero).

We can also cast a datatype to be a member of an array. The value being cast simply becomes the first element of the array:


Output will be 1985

Note that this shouldn’t be considered standard practice for adding items to an array because this only seems to work for the very first member of a newly created array. If it is cast against an existing array, that array will be wiped out, leaving only the newly cast value in the first position.

Any datatype can be cast as an object. The result is that the variable becomes an attribute of the object, the attribute having the name scalar:


The result is BMW

Adapting Data Types with Type Juggling


Variables are sometimes automatically cast to best fit the circumstances in which they are referenced. Consider the following snippet:


The outcome is the expected one; $total is assigned 20, converting the $count variable from a string to an integer in the process.

Here’s another example demonstrating PHP’s type-juggling capabilities:


The integer value at the beginning of the original $total string is used in the calculation. However, if it begins with anything other than a numerical representation, the value is 0. Let's consider another example:


In this example, a string is converted to Boolean type in order to evaluate the if statement.

Let's consider one last particularly interesting example. If a string used in a mathematical calculation includes ., e, or E (representing scientific notation), it will be evaluated as a float:


Variables

A variable is a symbol that can store different values at different times.

For example, suppose we create a web-based calculator capable of performing mathematical tasks. Of course, the user will want to input values of his choosing; therefore, the program must be able to dynamically store those values and perform calculations accordingly. At the same time, the programmer requires a user-friendly means for referring to these value-holders within the application. The variable accomplishes both tasks.

Variable Declaration
A variable always begins with a dollar sign, $, which is then followed by the variable name.
Variable names follow the same naming rules as identifiers.
That is, a variable name can begin with either a letter or an underscore and can consist of letters, underscores, numbers, or other ASCII characters ranging from 127 through 255.

The following are all valid variables:
  • $color
  • $operating_system
  • $_vai_variable
  • $kieuCach
Note that variables are case sensitive. For instance, the following variables bear no relation to each other:
  • $color
  • $Color
  • $COLOR
Value Assignment
Assignment by value simply involves copying the value of the assigned expression to the variable assignee. This is the most common type of assignment.

A few examples follow:
  • $color = "red";
  • $number = 12;
  • $age = 12;
  • $sum = 12 + "15"; // $sum = 27
Each of these variables possesses a copy of the expression assigned to it.
For example, $number and $age each possesses their own unique copy of the value 12.

Reference Assignment
the ability in PHP to assign variables by reference, which essentially means that you can
create a variable that refers to the same content as another variable does.

We can assign variables by reference by appending an ampersand (&) to the equal sign.

Example:

An alternative reference-assignment syntax is also supported, which involves appending the
ampersand to the front of the variable being referenced.

The following example adheres to this new syntax:


Variable Scope
We can declare our variables (by value or by reference) anywhere in a PHP script.

The location of the declaration greatly influences the realm in which a variable can be accessed. This accessibility domain is known as its scope.

PHP variables can be one of four scope types:
  • Local variables
  • Function parameters
  • Global variables
  • Static variables
Local Variables
A variable declared in a function is considered local. it can be referenced only in that function.

Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function.

Note that when we exit the function in which a local variable has been declared, that variable and its corresponding value are destroyed.

Local variables are helpful because they eliminate the possibility of unexpected side effects that can result from globally accessible variables that are modified, intentionally or not. Consider this listing:



Executing this listing results in the following:



Two different values for $x are output. This is because the $x located inside the assignx() function is local.
Modifying the value of the local $x has no bearing on any values located outside of the function.
On the same note, modifying the $x located outside of the function has no bearing on any variables contained in assignx().

Function Parameters
Any function that accepts arguments must declare those arguments in the function header. Although those arguments accept values that come from outside of the function, they are no longer accessible once the function has exited.

Function parameters are declared after the function name and inside parentheses (dấu ngoặc) . They are declared much like a typical variable would be:



Global Variables

In contrast to local variables, a global variable can be accessed in any part of the program.
To modify a global variable, however, it must be explicitly (rõ ràng) declared to be global in the function in which it is to be modified.
By placing the keyword global in front of the variable that should be recognized as global. Placing this keyword in front of an already existing variable tells PHP to use the variable having that name. Consider an example:



The displayed value of $somevar would be 16.

However, if we were to omit this line, global $somevar; then the variable $somevar would be assigned the value 1 because $somevar would then be considered local within the addit() function. This local declaration would be implicitly set to 0 and then incremented by 1 to display the value 1.

An alternative method for declaring a variable to be global is to use PHP’s $GLOBALS array.
Reconsidering the preceding example, we can use this array to declare the variable $somevar to be global:



This returns the following:



Static Variables
In contrast to the variables declared as function parameters, which are destroyed on the function’s exit, a static variable does not lose its value when the function exits and will still hold that value if the function is called again.

We can declare a variable as static simply by placing the keyword static in front of the variable name, like so:

STATIC $somevar;

Consider an example:



There will be 2 different cases that may result.
If the variable $count was not designated to be static (thus making $count a local variable), the outcome would be as follows:



Another case with variable $count which is static, it retains its previous value each time the function is executed. Therefore, the outcome is the following:



Static scoping is particularly useful for recursive functions (hàm đệ quy), a powerful programming concept in which a function repeatedly calls itself until a particular condition is met.

Thursday, 21 October 2010

PHP Basic

One of PHP’s advantages is that you can embed PHP code directly alongside HTML. For the code to do anything, the page must be passed to the PHP engine for interpretation. But the web server doesn’t just pass every page; rather, it passes only those pages identified by a specific file extension (typically .php). However, even selectively passing only certain pages to the engine would nonetheless be highly inefficient for the engine to consider every line as a potential PHP command. Therefore, the engine needs some means to immediately determine which areas of the page are PHP-enabled. This is logically accomplished by delimiting the PHP code.

Default Syntax
The default delimiter syntax opens with < ? php and concludes with ? >, like this:


Result:


Short-Tags

For less motivated typists, an even shorter delimiter syntax is available. Known as short-tags, this syntax forgoes the php reference required in the default syntax. However, to use this feature, we need to enable PHP’s short_open_tag directive. An example follows:


Important: Although short-tag delimiters are convenient, do not use them when creating PHP-driven software intended for redistribution. This is because this feature could potentially be disabled within the php.ini file.

When short-tags syntax is enabled and you want to quickly escape to and from PHP to output a bit of dynamic text, you can omit these statements using an output variation known as short-circuit syntax:

This is functionally equivalent to both of the following variations:




Embedding Multiple Code Blocks

We can escape to and from PHP as many times as required within a given page. For instance, the following example is perfectly acceptable:



As we can see here, any variables declared in a prior code block are remembered for later blocks, as is the case with the $date variable in this example.

Outputting Data to the Browser
There are many several methods to output the data on our browsers.

The print() Statement
All of the following are plausible print() statements:



All these statements produce identical output:



The print() statement’s return value is misleading because it will always return 1 regardless of outcome (the only outcome I’ve ever experienced using this statement is one in which the desired output is sent to the browser). This differs from the behavior of most other functions in the sense that their return value often serves as an indicator of whether the function executed as intended.

The echo() Statement

Alternatively, we could use the echo() statement for the same purposes as print().
To use echo(), just provide it with an argument just as was done with print():

echo "I love Ho Chi Minh city.";

echo() is capable of outputting multiple strings. The utility of this particular trait is questionable; using it seems to be a matter of preference more than anything else. Nonetheless, it’s available should you feel the need. Here’s an example:


or executing followings:



All above code will produce the following:


Which is faster, echo() or print()?
The fact that they are functionally interchangeable leaves many pondering this question. The answer is that the echo() function is a tad faster because it returns nothing, whereas print() will return 1 if the statement is successfully output. It’s rather unlikely that we’ll notice any speed difference, however, so we can consider the usage decision to be one of stylistic concern.

The printf() Statement
The printf() statement is ideal when you want to output a blend of static text and dynamic information stored within one or several variables. It’s ideal for two reasons.
  1. It neatly separates the static and dynamic data into two distinct sections, allowing for easy maintenance.
  2. printf() allows us to wield considerable control over how the dynamic information is rendered to the screen in terms of its type, precision, alignment, and position.
For example, suppose we wanted to insert a single dynamic integer value into an otherwise static string:


The output will be


In this example, %d is a placeholder known as a type specifier, and the d indicates an integer value will be placed in that position. When the printf() statement executes, the lone argument, 100, will be inserted into the placeholder.

Note that an integer is expected, so if we pass along a number including a decimal value (known as a float), it will be rounded down to the closest integer. For example: if we pass
along 100.2 or 100.6, then 100 will be output or pass along a string value such as “one hundred”, and 0 will be output, although if we pass along 123food, then 123 will be output.



The sprintf() Statement

The sprintf() statement is functionally identical to printf() except that the output is assigned to a string rather than rendered to the browser. The prototype follows:

string sprintf(string format [, mixed arguments])

An example follows:



Output:

Choosing a Code Editor and a Web Hosting Provider

Choosing a Code Editor
There are many code editors in the market. Here I recommend some commercial software and non-payment tools.
  • Adobe Dreamweaver family:
+ Intended to be a one-stop application, Dreamweaver CS3 supports all of the key technologies, such as Ajax, CSS, HTML, JavaScript, PHP, and XML, which together drive cutting-edge web sites.
+ In addition to allowing developers to create web pages in WYSIWYG (what-you-see-is-what-youget) fashion, Adobe’s Dreamweaver CS5 is considered by many to be the ultimate web designer’s toolkit, offers a number of convenient features for helping PHP developers more effectively write and manage code, including syntax highlighting, code completion, and the ability to easily save and reuse code snippets.
+ Dreamweaver cs5 is avaible for all Windows and Mac OS X platforms.

  • Notepad++
Notepad++ is a mature open source code editor and avowed Notepad replacement available for the Windows platform. Translated into dozens of languages, Notepad++ offers a wide array of convenient features one would expect of any capable IDE, including the ability to bookmark specific lines of a document for easy reference; syntax, brace, and indentation highlighting; powerful search facilities; macro recording for tedious tasks such as inserting templated comments; and much more.
  • Zend Studio
+ Zend Studio is far and away the most powerful PHP IDE of all commercial and open source offerings available today.
+ Zend Studio offers all of the features one would expect of an enterprise IDE, including comprehensive code completion, CVS and Subversion integration, internal and remote debugging, code profiling, and convenient code deployment processes.
+ Facilities integrating code with popular databases such as MySQL, Oracle, PostgreSQL, and SQLite are also offered, in addition to the ability to execute SQL queries and view and manage database schemas and data.
Choosing a Web Hosting Provider
Generally speaking, hosting providers can be broken into three categories:
1. Dedicated server hosting: involves leasing an entire web server, allowing your web site full reign over server CPU, disk space, and memory resources, as well as control over how the server is configured. This solution is particularly advantageous because we typically have complete control over the server’s administration but you don’t have to purchase or maintain the server hardware, hosting facility, or the network connection.
2. Shared server hosting: If your web site will require modest server resources, or ifyou don’t want to be bothered with managing the server, shared server hosting is likely the ideal solution. Shared hosting providers capitalize on these factors by hosting numerous web sites on a single server and using highly automated processes to manage system and network resources, data backups, and user support. The result is that they’re able to offer appealing pricing arrangements (many respected shared hosting providers offer no-contract monthly rates for as
low as $8 a month) while simultaneously maintaining high customer satisfaction.
3. Virtual private server hosting: A virtual private server blurs the line between a dedicated and shared server, providing each user with a dedicated operating system and the ability to install applications and fully manage the server by way of virtualization. Virtualization lets you run multiple distinct operating systems on the same server. The result is complete control for the user while simultaneously allowing the hosting provider to keep costs low and pass those savings along to the user.

Why should we use PHP rather than other language ?

Every user has specific reasons for using PHP to implement a mission-critical application, although one could argue that such motives tend to fall into four key categories: practicality, power, possibility, and price.
  • Practicality
+ From the very start, the PHP language was created with practicality in mind. allows the user to build powerful applications even with a minimum of knowledge. For instance, a useful PHP script can consist of as little as one line; unlike C, there is no need for the mandatory inclusion of libraries.
+ allows the user to build powerful applications even with a minimum of knowledge. For instance, a useful PHP script can consist of as little as one line; unlike C, there is no need for the mandatory inclusion of libraries.
+ is a loosely typed language, meaning there is no need to explicitly create, typecast, or destroy a variable. PHP handles such matters internally, creating variables on the fly as they are called in a script, and employing a best-guess formula for automatically typecasting variables.
+ PHP will also automatically destroy variables and return resources to the system when the script completes.
+ PHP allows the developer to concentrate almost exclusively on the final goal, namely a working application.

  • Power
PHP developers have almost 200 native libraries at their disposal, collectively containing well over 1,000 functions, in addition to thousands of third-party extensions. PHP is not only has ability to interface with databases, manipulate form information, and create pages dynamically but it can also do the following:
  • Create and manipulate Adobe Flash and Portable Document Format (PDF) files.
  • Evaluate a password for guessability by comparing it to language dictionaries andeasily broken patterns.
  • Parse even the most complex of strings using the POSIX and Perl-based regular expression libraries.
  • Authenticate users against login credentials stored in flat files, databases, and even Microsoft’s Active Directory.
  • Communicate with a wide variety of protocols, including LDAP, IMAP, POP3, NNTP, and DNS, among others.
  • Tightly integrate with a wide array of credit-card processing solutions.
  • Possibility
PHP developers are rarely bound to any single implementation solution. On the contrary, a user is typically fraught with choices offered by the language. For example, consider PHP’s array of database support options. Native support is offered for more than 25 database products, including mSQL, Microsoft SQL Server, MySQL, Oracle, PostgreSQL, etc.
  • Price
+ PHP is available free of charge! Since its inception, PHP has been without usage, modification, and redistribution restrictions. + Free of licensing restrictions imposed by most commercial products + Open development and auditing process + Participation is encouraged: Development teams are not limited to a particular organization. Anyone who has the interest and the ability is free to join the project. + The absence of member restrictions greatly enhances the talent pool for a given project, ultimately contributing to a higher-quality product.

Compared to other languages

After researching, I write down what differences among PHP, ASP/ ASP.NET and JSP & Serlvet beyond different areas and their advantages and disadvantages.

Sunday, 3 October 2010

Introduction about PHP

What is PHP?

PHP is a short name of Personal Home Page or stands for Hypertext Preprocessor. It is a server side, HTML embeded scripting language used to create dynamic web pages.

Much of its syntax is borrowed from C, Java and Perl with some unique features thrown in.

In HTML pages, PHP code is enclosed in special PHP tags. When visitors open the pages, the server processes the PHP code and then sends the output (not the PHP code itself) to the visitor's browser. This means php code is not like JavaScript code which people can copy from our site and use it on their site.

PHP offers excellent connectivity to many databases including MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, and Generic ODBC. The popular PHP-MySQL combination (both are open-source products) is available on almost every UNIX host. Being web-oriented, PHP also contains all the functions to do things on the Internet - connecting to remote servers, checking email via POP3 or IMAP, url encoding, setting cookies, redirecting, etc.


There are many versions of PHP, what different(s) between them?

PHP4: added to several enterprise-level improvement to the language, including the following:
  • Improved resource handling.
  • Object-oriented support: a degree of object-oriented functionality is incorporated in version 4, although it was largely considered an unexceptional and even poorly conceived implementation. Nonetheless, the new features played an important role in attracting users used to working with traditional object-oriented programming (OOP) languages. Standard class and object development methodologies were made available in addition to features such as object overloading and run-time class information.
  • Native session-handling support: This feature offered developers a means for tracking user activity and preferences with unparalleled efficiency and ease.
  • ISAPI support: ISAPI support gave users the ability to use PHP in conjunction with Microsoft’s IIS Web server. A later joint collaboration between Zend and Microsoft greatly improved IIS’ PHP support using FastCGI.
  • Native COM/DCOM support: Another bonus for Windows users is PHP 4’s ability
    to access and instantiate COM objects. This functionality opened up a wide range of interoperability with Windows applications.
  • Native Java support: In another boost to PHP’s interoperability, version 4 offered support for binding to Java objects from a PHP application.
  • Perl Compatible Regular Expressions (PCRE) library: The Perl language has long been heralded as the reigning royalty of the string-parsing kingdom.The developers knew that powerful regular expression functionality would play a major role in the widespread acceptance of PHP and opted to simply incorporate Perl’s functionality rather than reproduce it, rolling the PCRE library package into PHP’s default distribution.
PHP5: Version 5 was yet another watershed in the evolution of the PHP language. Although previous major releases had enormous numbers of new library additions, version 5 contained improvements over existing functionality and added several features commonly associated with mature programming language architectures:
  • Vastly improved object-oriented capabilities:Version 5 includednumerous functional additions such as explicit constructors and destructors,object cloning, class abstraction, variable scope, and interfaces, and a major improvement regarding how PHP handles object management.
  • Try/catch exception handling: Devising error-handling strategies within this problem, version 5 added support for exception handling. Long a mainstay of error management in many languages, such as C++, C#, Python, and Java, exception handling offers an excellent means for standardizing your error reporting logic
  • Improved XML and Web Services support: As of version 5, XML support is based on the libxml2 library; and a new and rather promising extension for parsing and manipulating XML, known as SimpleXML, was introduced.
  • Native support for SQLite: Always keen on providing developers with a multitude of choices, support was added for the powerful yet compact SQLite database server (www.sqlite.org). SQLite offers a convenient solution for developers looking for many of the features found in some of the heavyweight database products without incurring the accompanying administrative overhead.
PHP6: has been concurrently developed alongside PHP 5.X for several years, with the primary goal of adding Unicode support to the language.