PHP
From DocForge
PHP is an interpreted programming language most frequently used in the creation of web applications and web templating. Originally developed to quickly script dynamic HTML content, its syntax now draws upon elements found in C, Perl and Java. PHP supports both procedural programming and object oriented programming.
The PHP interpreter is run as a web server module, through CGI, or independently at the command line. It takes input from a file or stream containing text and PHP instructions and outputs another stream of data to return to the client. Since PHP version 4, the PHP parser compiles input to produce bytecode for processing by the Zend Engine. The Zend Engine II is the core of PHP 5.
Contents |
[edit] Reference
- PHP/Variable
- Control flow statements
- Object oriented programming
- PHP/Functions and language constructs
- PHP/Superglobals
[edit] Common Methodologies
[edit] Basic Syntax
A Hello World code example for PHP:
<?php
echo 'Hello, World!';
?>
PHP only parses code within its delimiters, typically <?php ?>. Anything outside its delimiters is sent directly to output and not parsed by PHP. The example above outputs:
Hello, World!
The primary purpose of delimiting the code is to allow PHP statements to be embedded within HTML documents, for example:
<?php
// PHP statements
?>
Regular HTML
<?php
// More PHP statements
?>
The short-tag configuration option simplifies the delimiters to be <? and ?>. This also alows for easy templating by defining variables above your output area with the <?= operand. For example:
<?php
// Code
$hello = "Hello World";
// Code
?>
and then later in html:
<!-- lots of html -->
<div>
<p><?=$hello?></p>
</div>
Variables are prefixed with a dollar symbol and a type isn't specified in advance. Variable names are case sensitive while function and class names are not. Both double-quoted ("") and heredoc strings allow the ability to embed a variable's value into a string.
PHP treats new lines as whitespace, in the manner of a free-form language (except when inside string quotes). Statements are terminated by a semicolon, except in a few special cases.
PHP has three types of comment syntax: /* */ which serves as block comments, and // and # which are used for inline comments.
[edit] Data Types
PHP stores whole numbers in a platform-dependent range. Integer variables can be assigned using decimal (positive and negative), octal and hexadecimal notations. Real numbers are also stored in a platform-specific range. They can be specified using floating point notation, or two forms of scientific notation.
PHP has a native boolean type. Its type conversion rules allow non-zero values to be interpreted as true and zero as false, as in Perl.
The null data type represents a variable that has no value.
Variables of the resource type represent references to resources external to the interpreter. These are typically created by functions from a particular extension. Examples include file, image and database resources.
Arrays support both numeric and string indices, and are heterogeneous. Arrays can contain elements of any type that PHP can handle, including resources, objects, and even other arrays. Order is preserved in lists of values and in hashes with both keys and values, and the two can be intermingled.
[edit] Objects
PHP offers object oriented programming functionality, including classes, interfaces, and public/private/protected visibility of member variables and methods. Instantiated objects are referenced by handle, effectively similar to a pointer. In this way objects are passed around by reference and not copied unless explicitly cloned.
PHP objects are instances of classes defined by the developer or the PHP runtime environment. By default, objects in PHP are assigned and passed by reference as of version 5 of the language. This means that two variables both assigned to the same object are acting on the exact same object and not copies.
[edit] Resources
[edit] Libraries and Extensions
PHP allows developers to write extensions in C to add functionality to the PHP core language. These can then be compiled into PHP or loaded dynamically at runtime. PHP includes a large number of free and open source libraries with the core build. These include interfaces to common external systems such as MySQL, SQLite, LDAP, memcache, etc. Interfaces are also available to many common shared libraries, such as GD, OpenSSL, and curl.
[edit] PECL / PEAR
The PHP Extension Community Library (PECL) project is a repository for extensions to the PHP language. The PHP Extension and Application Repository (PEAR) project provides reusable libraries and components for PHP development.
[edit] Accelerators and Optimizers
The PHP engine directly executes human-readable source code. Accelerators can be added to cache a compiled form of PHP scripts and also perform code optimizations. A few are available, but APC is the most commonly distributed and may become a default in a future version of PHP.
[edit] Debuggers and Profilers
PHP debuggers and profilers include APD and Xdebug. These assist developers in walking through executing code to find errors and bottlenecks.
[edit] Templating Engines
While PHP itself can serve as a templating language, additional templating engines can provide a simpler way to perform common tasks. Popular templating engines include Smarty and Twig.
[edit] PHP Functions
In PHP, there are hundreds of built-in functions. You can create your own functions. A function will be executed by a call to the function. You may call a function from anywhere within a page.
// Define a custom function
function functionName() {
[code to be executed]
}
To add more functionality to a function, you can define parameters. A parameter is just like a variable. Parameters are specified after the function name, inside the parentheses. To let a function return a value, use the return statement:
<html>
<body>
<?php
function add($x,$y) {
$total=$x+$y;
return $total;
}
echo "6 + 9 = " . add(6,9);
?>
</body>
</html>
Page output:
<html>
<body>
6 + 9 = 15
</body>
</html>
[edit] Useful Functions
[edit] Formatting a Large Amount of Seconds
If you save dates in timestamp format, you may find a need to display the time difference between dates. The easiest way to do it in PHP isn't necessarily the most efficient, but it's a nice trick that's easy to read and maintain:
define('DAY', 86400);
$calculated_value = mktime(0,0,0,1,1,2000) + $value;
if($value > DAY * 365){
$result .= date('y', $calculated_value);
$result .= 'y ';
}
if($value > DAY * 30){
$result .= date('n', $calculated_value);
$result .= 'mo ';
}
if($value > DAY){
$result .= date('j', $calculated_value);
$result .= 'd ';
}
if($value > 3600){
$result .= date('G', $calculated_value);
$result .= 'h ';
}
if($value > 60){
$result .= date('i', $calculated_value);
$result .= 'm ';
}
$result .= date('s', $calculated_value);
$result .= 's ';
This code is pretty verbose for clarity, but it can be a lot briefer and more efficient. I needed to use this in a report where it was going to run once for each row, so I used this:
$parts = array('y'=>'y','n'=>'mo','j'=>'d','G'=>'h','i'=>'m','s'=>'s');
$parts = array_combine(explode(':', date(implode(':', array_keys($parts)),
mktime(0,0,0,1,1,2000) + $value)), array_values($parts));
$result = '';
foreach($parts as $num => $mark){
if($num+0){
$result .= "$num$mark ";
}
}
[edit] Replacing "smart" quotes with "real" quotes
Microsoft Windows has a habit of replacing standard quotes with "smart" quotes, sometimes called "curly" quotes. Instead of falling straight down these quotes curl inward toward the text they enclose. These quotation marks aren't from the standard ASCII table. Therefore when they're copied and pasted into a web browser they often cause string issues with web server software. To convert these quotes to their standard ASCII equivalents their extended ASCII codes are needed. This PHP code will perform the required replacement:
$from = array(chr(145), chr(146), chr(147), chr(148));
$to = array("'", "'", '"', '"');
$string = str_replace($from, $to, $string);