learnxinyminutes-docs/php.html.markdown

576 lines
12 KiB
Markdown
Raw Normal View History

2013-06-27 13:42:07 +04:00
---
language: php
author: Malcolm Fell
author_url: http://emarref.net/
---
This document describes PHP 5+.
## [Basic Syntax](http://www.php.net/manual/en/language.basic-syntax.php)
2013-06-27 20:49:03 +04:00
All statements must end with a semi-colon; All PHP code must be between <?php and ?> tags. PHP can also be
configured to respect the [short open tags](http://www.php.net/manual/en/ini.core.php#ini.short-open-tag) <? and ?>.
2013-06-27 13:42:07 +04:00
## [Comments](http://www.php.net/manual/en/language.basic-syntax.comments.php)
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
// Two forward slashes start a one-line comment.
# So will a hash (aka pound symbol) but // is more common
/*
Surrounding text in slash-asterisk and asterisk-slash
makes it a multi-line comment.
*/
```
## [Types](http://www.php.net/manual/en/language.types.php)
2013-06-27 20:49:03 +04:00
Types are [weakly typed](http://en.wikipedia.org/wiki/Strong_and_weak_typing) and begin with the $ symbol.
A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
2013-06-27 13:42:07 +04:00
### Scalars
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
// Boolean values are case-insensitive
$boolean = true; // or TRUE or True
$boolean = false; // or FALSE or False
// Integers
$integer = 1234; // decimal number
$integer = -123; // a negative number
$integer = 0123; // octal number (equivalent to 83 decimal)
$integer = 0x1A; // hexadecimal number (equivalent to 26 decimal)
// Floats (aka doubles)
$float = 1.234;
$float = 1.2e3;
2013-06-27 13:42:07 +04:00
$float = 7E-10;
// Arithmetic
$sum = $number + $float;
$difference = $number - $float;
$product = $number * $float;
$quotient = $number / $float;
// Shorthand arithmetic
2013-06-27 20:49:03 +04:00
$number += 1; // Add 1 to $number
$number++; // Add 1 to $number after it is used
++$number; // Add 1 to $number before it is used.
$number /= $float // Divide and assign the quotient to $number
// Strings should be enclosed in single quotes;
$sgl_quotes = '$String'; // => '$String'
// Avoid using double quotes except to embed other variables
$dbl_quotes = "This is a $sgl_quotes." // => 'This is a $String'
// Escape special characters with backslash
$escaped = "This contains a \t tab character.";
// Enclose a variable in curly braces if needed
$money = "I have $${integer} in the bank."
// Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners
2013-06-27 13:42:07 +04:00
$nowdoc = <<<'END'
Multi line
string
END;
2013-06-27 20:49:03 +04:00
2013-06-27 13:42:07 +04:00
$heredoc = <<<END
Multi line
$sgl_quotes
END; // Nowdoc syntax is available in PHP 5.3.0
// Manipulation
2013-06-28 00:48:53 +04:00
$concatenated = $sgl_quotes . $dbl_quotes;
2013-06-27 13:42:07 +04:00
```
### Compound
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
// Arrays
$array = array(1, 2, 3);
$array = [1, 2, 3]; // As of PHP 5.4
$string = ["One", "Two", "Three"];
$string[0]; // Holds the value "One";
// Associative arrays, known as hashmaps in some languages.
$associative = ["One" => 1, "Two" => 2, "Three" => 3];
$associative["One"]; // Holds the value 1
```
## Output
```php
2013-06-27 20:49:03 +04:00
<?php
echo('Hello World!');
// Prints Hello World! to stdout.
// Stdout is the web page if running in a browser.
2013-06-27 13:42:07 +04:00
print('Hello World!'); // The same as echo
2013-06-27 20:49:03 +04:00
// echo is actually a language construct, so you can drop the parentheses.
echo 'Hello World!';
2013-06-28 00:49:58 +04:00
print 'Hello World!'; // So is print
2013-06-28 05:10:45 +04:00
2013-06-27 13:42:07 +04:00
echo 100;
echo $variable;
2013-06-27 20:49:03 +04:00
echo function_result();
2013-06-27 13:42:07 +04:00
2013-06-27 20:49:03 +04:00
// If short open tags are configured, or your PHP version is
// 5.4.0 or greater, you can use the short echo syntax
2013-06-27 13:42:07 +04:00
<?= $variable ?>
```
## [Operators](http://www.php.net/manual/en/language.operators.php)
### Assignment
```php
2013-06-27 20:49:03 +04:00
<?php
$x = 1;
$y = 2;
$x = $y; // A now contains the same value sa $y
2013-06-28 05:10:45 +04:00
$x = &$y;
// $x now contains a reference to $y. Changing the value of
// $x will change the value of $y also, and vice-versa.
2013-06-27 13:42:07 +04:00
```
### Comparison
```php
2013-06-27 20:49:03 +04:00
<?php
// These comparisons will always be true, even if the types aren't the same.
2013-06-27 13:42:07 +04:00
$a == $b // TRUE if $a is equal to $b after type juggling.
$a != $b // TRUE if $a is not equal to $b after type juggling.
$a <> $b // TRUE if $a is not equal to $b after type juggling.
2013-06-27 20:49:03 +04:00
$a < $b // TRUE if $a is strictly less than $b.
2013-06-27 13:42:07 +04:00
$a > $b // TRUE if $a is strictly greater than $b.
$a <= $b // TRUE if $a is less than or equal to $b.
$a >= $b // TRUE if $a is greater than or equal to $b.
2013-06-28 05:13:02 +04:00
// The following will only be true if the values match and are the same type.
$a === $b // TRUE if $a is equal to $b, and they are of the same type.
$a !== $b // TRUE if $a is not equal to $b, or they are not of the same type.
1 == '1' // TRUE
1 === '1' // FALSE
2013-06-27 13:42:07 +04:00
```
## [Type Juggling](http://www.php.net/manual/en/language.types.type-juggling.php)
Variables can be converted between types, depending on their usage.
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
$integer = 1;
echo $integer + $integer; // Outputs 2;
$string = '1';
2013-06-27 20:49:03 +04:00
echo $string + $string;
// Also outputs 2 because the + operator converts the strings to integers
2013-06-27 13:42:07 +04:00
$string = 'one';
2013-06-27 20:49:03 +04:00
echo $string + $string;
// Outputs 0 because the + operator cannot cast the string 'one' to a number
2013-06-28 00:57:25 +04:00
```
2013-06-27 13:42:07 +04:00
2013-06-28 00:57:25 +04:00
Type casting can be used to treat a variable as another type temporarily by using cast operators in parentheses.
2013-06-27 13:42:07 +04:00
2013-06-28 00:57:25 +04:00
```php
2013-06-27 13:42:07 +04:00
$boolean = (boolean) $integer; // $boolean is true
$zero = 0;
$boolean = (boolean) $zero; // $boolean is false
$integer = 5;
2013-06-27 20:49:03 +04:00
$string = strval($integer);
// There are also dedicated functions for casting most types
2013-06-27 13:42:07 +04:00
$var = null; // Null value
```
## [Control Structures](http://www.php.net/manual/en/language.control-structures.php)
### If Statements
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
if (/* test */) {
2013-06-27 20:49:03 +04:00
// Do something
2013-06-27 13:42:07 +04:00
}
if (/* test */) {
2013-06-27 20:49:03 +04:00
// Do something
2013-06-27 13:42:07 +04:00
} else {
2013-06-27 20:49:03 +04:00
// Do something else
2013-06-27 13:42:07 +04:00
}
if (/* test */) {
2013-06-27 20:49:03 +04:00
// Do something
2013-06-27 13:42:07 +04:00
} elseif(/* test2 */) {
2013-06-27 20:49:03 +04:00
// Do something else, only if test2
2013-06-27 13:42:07 +04:00
}
if (/* test */) {
2013-06-27 20:49:03 +04:00
// Do something
2013-06-27 13:42:07 +04:00
} elseif(/* test2 */) {
2013-06-27 20:49:03 +04:00
// Do something else, only if test2
2013-06-27 13:42:07 +04:00
} else {
2013-06-27 20:49:03 +04:00
// Do something default
2013-06-27 13:42:07 +04:00
}
2013-06-27 20:49:03 +04:00
?>
2013-06-27 13:42:07 +04:00
<?php if (/* test */): ?>
2013-06-28 00:57:52 +04:00
This is displayed if the test is truthy.
2013-06-27 13:42:07 +04:00
<?php else: ?>
2013-06-28 00:57:52 +04:00
This is displayed otherwise.
2013-06-27 13:42:07 +04:00
<?php endif; ?>
```
### Switch statements
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
switch ($variable) {
2013-06-27 20:49:03 +04:00
case 'one':
// Do something if $variable == 'one'
2013-06-27 13:42:07 +04:00
break;
case 'two':
case 'three':
2013-06-27 20:49:03 +04:00
// Do something if $variable is either 'two' or 'three'
2013-06-27 13:42:07 +04:00
break;
default:
2013-06-27 20:49:03 +04:00
// Do something by default
2013-06-27 13:42:07 +04:00
}
```
### Loops
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
$i = 0;
while ($i < 5) {
2013-06-27 20:49:03 +04:00
echo $i++;
2013-06-27 13:42:07 +04:00
}
$i = 0;
do {
2013-06-27 20:49:03 +04:00
echo $i++;
2013-06-27 13:42:07 +04:00
} while ($i < 5);
for ($x = 0; $x < 10; $x++) {
2013-06-27 20:49:03 +04:00
echo $x; // Will echo 0 - 9
2013-06-27 13:42:07 +04:00
}
$wheels = ["bicycle" => 2, "car" => 4];
foreach ($wheels as $vehicle => $wheel_count) {
2013-06-27 20:49:03 +04:00
echo "A $vehicle has $wheel_count wheels";
2013-06-27 13:42:07 +04:00
}
// This loop will stop after outputting 2
$i = 0;
while ($i < 5) {
if ($i == 3) {
2013-06-27 20:49:03 +04:00
break; // Exit out of the while loop and continue.
2013-06-27 13:42:07 +04:00
}
2013-06-27 20:49:03 +04:00
echo $i++;
2013-06-27 13:42:07 +04:00
}
// This loop will output everything except 3
$i = 0;
while ($i < 5) {
2013-06-27 20:49:03 +04:00
if ($i == 3) {
continue; // Skip this iteration of the loop
2013-06-27 13:42:07 +04:00
}
2013-06-27 20:49:03 +04:00
echo $i++;
2013-06-27 13:42:07 +04:00
}
```
## Functions
Functions are created with the ```function``` keyword.
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
function my_function($my_arg) {
2013-06-27 20:49:03 +04:00
$my_variable = 1;
2013-06-27 13:42:07 +04:00
}
// $my_variable and $my_arg cannot be accessed outside of the function
```
Functions may be invoked by name.
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
my_function_name();
$variable = get_something(); // A function may return a value
```
2013-06-27 20:49:03 +04:00
A valid function name starts with a letter or underscore, followed by any
number of letters, numbers, or underscores. There are three ways to declare functions.
2013-06-27 13:42:07 +04:00
### [User-defined](http://www.php.net/manual/en/functions.user-defined.php)
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-28 05:13:02 +04:00
function my_function_name ($arg_1, $arg_2) {
// $arg_1 and $arg_2 are required
2013-06-27 13:42:07 +04:00
}
// Functions may be nested to limit scope
function outer_function ($arg_1 = null) { // $arg_1 is optional
2013-06-27 20:49:03 +04:00
function inner_function($arg_2 = 'two') { // $arg_2 will default to 'two'
2013-06-27 13:42:07 +04:00
}
}
2013-06-28 05:13:02 +04:00
// inner_function() does not exist and cannot be called until
// outer_function() is called
2013-06-27 13:42:07 +04:00
```
2013-06-28 01:11:27 +04:00
This enables [currying](http://en.wikipedia.org/wiki/Currying) in PHP.
```php
function foo ($x, $y, $z) {
echo "$x - $y - $z";
}
function bar ($x, $y) {
return function ($z) use ($x, $y) {
foo($x, $y, $z);
};
}
$bar = bar('A', 'B');
$bar('C');
```
2013-06-27 13:42:07 +04:00
### [Variable](http://www.php.net/manual/en/functions.variable-functions.php)
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
$function_name = 'my_function_name';
$function_name(); // will execute the my_function_name() function
```
### [Anonymous](http://www.php.net/manual/en/functions.anonymous.php)
Similar to variable functions, functions may be anonymous.
```php
2013-06-27 20:49:03 +04:00
<?php
function my_function($callback) {
$callback('My argument');
}
my_function(function ($my_argument) {
2013-06-27 20:49:03 +04:00
// do something
2013-06-27 13:42:07 +04:00
});
// Closure style
$my_function = function() {
2013-06-27 20:49:03 +04:00
// Do something
2013-06-27 13:42:07 +04:00
};
$my_function();
```
## [Classes](http://www.php.net/manual/en/language.oop5.php)
Classes are defined with the ```class``` keyword.
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
class MyClass {
2013-06-27 20:49:03 +04:00
const MY_CONST = 'value';
2013-06-27 13:42:07 +04:00
static $staticVar = 'something';
2013-06-27 20:49:03 +04:00
public $property = 'value'; // Properties must declare their visibility
2013-06-27 13:42:07 +04:00
}
echo MyClass::MY_CONST; // Outputs "value";
final class YouCannotExtendMe {
}
```
2013-06-29 17:53:49 +04:00
Classes are instantiated with the ```new``` keyword. Functions are referred to as
2013-06-27 20:49:03 +04:00
methods if they belong to a class.
2013-06-27 13:42:07 +04:00
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
class MyClass {
2013-06-27 20:49:03 +04:00
function myFunction() {
2013-06-27 13:42:07 +04:00
}
2013-06-28 05:10:45 +04:00
final function youCannotOverrideMe() {
2013-06-27 13:42:07 +04:00
}
2013-06-28 05:10:45 +04:00
public static function myStaticMethod() {
2013-06-27 13:42:07 +04:00
}
}
$cls = new MyClass(); // The parentheses are optional.
echo MyClass::$staticVar; // Access to static vars
echo $cls->property; // Access to properties
MyClass::myStaticMethod(); // myStaticMethod cannot be run on $cls
```
PHP offers some [magic methods](http://www.php.net/manual/en/language.oop5.magic.php) for classes.
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
class MyClass {
2013-06-27 20:49:03 +04:00
private $property;
2013-06-27 13:42:07 +04:00
public function __get($key)
{
2013-06-27 20:49:03 +04:00
return $this->$key;
2013-06-27 13:42:07 +04:00
}
2013-06-27 13:42:07 +04:00
public function __set($key, $value)
{
2013-06-27 20:49:03 +04:00
$this->$key = $value;
2013-06-27 13:42:07 +04:00
}
}
$x = new MyClass();
2013-06-27 20:49:03 +04:00
echo $x->property; // Will use the __get() method
$x->property = 'Something'; // Will use the __set() method
2013-06-27 13:42:07 +04:00
```
2013-06-28 01:21:09 +04:00
Classes can be abstract (using the ```abstract``` keyword), extend other classes (using the ```extends``` keyword) and
implement interfaces (using the ```implements``` keyword). An interface is declared with the ```interface``` keyword.
2013-06-27 13:42:07 +04:00
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
interface InterfaceOne
{
2013-06-27 20:49:03 +04:00
public function doSomething();
2013-06-27 13:42:07 +04:00
}
interface InterfaceTwo
{
2013-06-27 20:49:03 +04:00
public function doSomething();
2013-06-27 13:42:07 +04:00
}
abstract class MyAbstractClass implements InterfaceOne
{
}
class MyClass extends MyAbstractClass implements InterfaceTwo
{
}
// Classes can implement more than one interface
class SomeOtherClass implements InterfaceOne, InterfaceTwo
{
}
```
### [Namespaces](http://www.php.net/manual/en/language.namespaces.rationale.php)
By default, classes exist in the global namespace, and can be explicitly called with a backslash.
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
$cls = new \MyClass();
```
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
namespace My\Namespace;
class MyClass
{
}
$cls = new My\Namespace\MyClass;
```
Or from within another namespace.
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
namespace My\Other\Namespace;
use My\Namespace\MyClass;
$cls = new MyClass();
```
Or you can alias the namespace;
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
namespace My\Other\Namespace;
use My\Namespace as SomeOtherNamespace;
$cls = new SomeOtherNamespace\MyClass();
```
### [Traits](http://www.php.net/manual/en/language.oop5.traits.php)
Traits are available since PHP 5.4.0 and are declared using the ```trait``` keyword.
```php
2013-06-27 20:49:03 +04:00
<?php
2013-06-27 13:42:07 +04:00
trait MyTrait {
2013-06-27 20:49:03 +04:00
public function myTraitMethod()
2013-06-27 13:42:07 +04:00
{
2013-06-27 20:49:03 +04:00
// Do something
2013-06-27 13:42:07 +04:00
}
}
class MyClass
{
2013-06-27 20:49:03 +04:00
use MyTrait;
2013-06-27 13:42:07 +04:00
}
$cls = new MyClass();
$cls->myTraitMethod();
```
## More Information
Visit the [official PHP documentation](http://www.php.net/manual/) for reference and community input.
If you're interested in up-to-date best practices, visit [PHP The Right Way](http://www.phptherightway.com/).
2013-06-27 20:35:59 +04:00
If you're coming from a language with good package management, check out [Composer](http://getcomposer.org/).