learnxinyminutes-docs/php.html.markdown

821 lines
18 KiB
Markdown
Raw Normal View History

2013-06-27 09:42:07 +00:00
---
2014-10-12 19:24:52 +00:00
language: PHP
2013-07-04 05:59:13 +00:00
contributors:
2013-07-15 15:19:23 +00:00
- ["Malcolm Fell", "http://emarref.net/"]
- ["Trismegiste", "https://github.com/Trismegiste"]
2013-06-30 03:19:14 +00:00
filename: learnphp.php
2013-06-27 09:42:07 +00:00
---
This document describes PHP 5+.
```php
2013-08-02 16:40:22 +00:00
<?php // PHP code must be enclosed with <?php tags
2013-06-27 16:49:03 +00:00
2013-11-09 18:29:14 +00:00
// If your php file only contains PHP code, it is best practice
2015-10-17 01:19:08 +00:00
// to omit the php closing tag to prevent accidental output.
2013-06-30 03:25:21 +00:00
2013-06-27 09:42:07 +00: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.
*/
2013-06-29 21:34:54 +00:00
// Use "echo" or "print" to print output
print('Hello '); // Prints "Hello " with no line break
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
// () are optional for print and echo
2013-06-30 03:25:21 +00:00
echo "World\n"; // Prints "World" with a line break
2013-06-29 21:34:54 +00:00
// (all statements must end with a semicolon)
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
// Anything outside <?php tags is echoed automatically
2013-08-02 16:40:22 +00:00
?>
Hello World Again!
2013-06-27 16:49:03 +00:00
<?php
2013-06-29 21:34:54 +00:00
/************************************
* Types & Variables
*/
// Variables 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 09:42:07 +00:00
// Boolean values are case-insensitive
2013-06-30 03:25:21 +00:00
$boolean = true; // or TRUE or True
2013-06-27 09:42:07 +00:00
$boolean = false; // or FALSE or False
// Integers
$int1 = 12; // => 12
$int2 = -12; // => -12
$int3 = 012; // => 10 (a leading 0 denotes an octal number)
2013-06-29 21:34:54 +00:00
$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal)
2013-06-27 09:42:07 +00:00
// Floats (aka doubles)
$float = 1.234;
$float = 1.2e3;
2013-06-27 09:42:07 +00:00
$float = 7E-10;
// Delete variable
2015-05-14 21:30:15 +00:00
unset($int1);
2013-06-27 09:42:07 +00:00
// Arithmetic
2013-06-30 03:25:21 +00:00
$sum = 1 + 1; // 2
2013-06-29 21:34:54 +00:00
$difference = 2 - 1; // 1
2013-06-30 03:25:21 +00:00
$product = 2 * 2; // 4
$quotient = 2 / 1; // 2
2013-06-27 09:42:07 +00:00
// Shorthand arithmetic
2013-06-29 21:34:54 +00:00
$number = 0;
2013-06-30 03:25:21 +00:00
$number += 1; // Increment $number by 1
echo $number++; // Prints 1 (increments after evaluation)
2013-09-15 06:15:53 +00:00
echo ++$number; // Prints 3 (increments before evaluation)
2013-06-29 21:34:54 +00:00
$number /= $float; // Divide and assign the quotient to $number
2013-06-27 16:49:03 +00:00
// Strings should be enclosed in single quotes;
$sgl_quotes = '$String'; // => '$String'
// Avoid using double quotes except to embed other variables
2013-06-30 03:25:21 +00:00
$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.'
2013-06-27 16:49:03 +00:00
2013-06-29 21:34:54 +00:00
// Special characters are only escaped in double quotes
2013-06-30 03:25:21 +00:00
$escaped = "This contains a \t tab character.";
2013-06-29 21:34:54 +00:00
$unescaped = 'This just contains a slash and a t: \t';
2013-06-27 16:49:03 +00:00
// Enclose a variable in curly braces if needed
2013-06-29 21:34:54 +00:00
$money = "I have $${number} in the bank.";
2013-06-27 16:49:03 +00:00
// Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners
2013-06-27 09:42:07 +00:00
$nowdoc = <<<'END'
Multi line
string
END;
2013-06-27 16:49:03 +00:00
2013-06-29 21:34:54 +00:00
// Heredocs will do string interpolation
2013-06-27 09:42:07 +00:00
$heredoc = <<<END
Multi line
$sgl_quotes
2013-06-29 21:34:54 +00:00
END;
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
// String concatenation is done with .
echo 'This string ' . 'is concatenated';
2013-06-27 09:42:07 +00:00
2015-10-17 00:11:37 +00:00
// Strings can be passed in as parameters to echo
echo 'Multiple', 'Parameters', 'Valid'; // Returns 'MultipleParametersValid'
2013-06-27 09:42:07 +00:00
/********************************
* Constants
*/
2013-09-08 20:31:46 +00:00
// A constant is defined by using define()
// and can never be changed during runtime!
// a valid constant name starts with a letter or underscore,
// followed by any number of letters, numbers, or underscores.
define("FOO", "something");
// access to a constant is possible by calling the choosen name without a $
echo FOO; // Returns 'something'
echo 'This outputs '.FOO; // Returns 'This ouputs something'
2013-06-29 21:34:54 +00:00
/********************************
* Arrays
*/
2013-06-27 16:49:03 +00:00
2013-06-29 21:34:54 +00:00
// All arrays in PHP are associative arrays (hashmaps),
2013-06-27 09:42:07 +00:00
// Associative arrays, known as hashmaps in some languages.
2013-06-29 21:34:54 +00:00
// Works with all PHP versions
$associative = array('One' => 1, 'Two' => 2, 'Three' => 3);
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
// PHP 5.4 introduced a new syntax
$associative = ['One' => 1, 'Two' => 2, 'Three' => 3];
2013-06-30 03:25:21 +00:00
echo $associative['One']; // prints 1
2013-06-29 21:34:54 +00:00
// List literals implicitly assign integer keys
$array = ['One', 'Two', 'Three'];
echo $array[0]; // => "One"
// Add an element to the end of an array
$array[] = 'Four';
2015-10-17 00:11:37 +00:00
// or
array_push($array, 'Five');
// Remove element from array
2013-09-08 20:31:46 +00:00
unset($array[3]);
2013-06-29 21:34:54 +00:00
/********************************
* Output
*/
2013-06-27 16:49:03 +00:00
echo('Hello World!');
// Prints Hello World! to stdout.
// Stdout is the web page if running in a browser.
2013-06-27 09:42:07 +00:00
print('Hello World!'); // The same as echo
2013-06-27 16:49:03 +00:00
// echo and print are language constructs too, so you can drop the parentheses
2013-06-27 16:49:03 +00:00
echo 'Hello World!';
print 'Hello World!';
2013-06-28 01:10:45 +00:00
2013-06-29 21:34:54 +00:00
$paragraph = 'paragraph';
2013-06-30 03:25:21 +00:00
echo 100; // Echo scalar variables directly
echo $paragraph; // or variables
2013-06-27 09:42:07 +00:00
2013-06-27 16:49:03 +00: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-29 21:34:54 +00:00
?>
<p><?= $paragraph ?></p>
2013-06-27 16:49:03 +00:00
<?php
$x = 1;
$y = 2;
2013-06-30 03:25:21 +00:00
$x = $y; // $x now contains the same value as $y
2013-06-29 21:34:54 +00:00
$z = &$y;
2013-06-30 03:25:21 +00:00
// $z now contains a reference to $y. Changing the value of
// $z will change the value of $y also, and vice-versa.
// $x will remain unchanged as the original value of $y
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
echo $x; // => 2
echo $z; // => 2
$y = 0;
echo $x; // => 2
echo $z; // => 0
2013-06-27 09:42:07 +00:00
// Dumps type and value of variable to stdout
var_dump($z); // prints int(0)
// Prints variable to stdout in human-readable format
print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three )
2013-06-27 16:49:03 +00:00
2013-06-29 21:34:54 +00:00
/********************************
* Logic
*/
$a = 0;
$b = '0';
$c = '1';
$d = '1';
2013-06-29 21:34:54 +00:00
// assert throws a warning if its argument is not true
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
// These comparisons will always be true, even if the types aren't the same.
assert($a == $b); // equality
assert($c != $a); // inequality
assert($c <> $a); // alternative inequality
2013-06-29 21:34:54 +00:00
assert($a < $c);
assert($c > $b);
assert($a <= $b);
assert($c >= $d);
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
// The following will only be true if the values match and are the same type.
assert($c === $d);
assert($a !== $d);
2014-01-17 06:38:24 +00:00
assert(1 === '1');
2013-06-29 21:34:54 +00:00
assert(1 !== '1');
2013-06-27 09:42:07 +00:00
// 'Spaceship' operator (since PHP 7)
// Returns 0 if values on either side are equal
// Returns 1 if value on the left is greater
// Returns -1 if the value on the right is greater
2015-10-02 16:24:45 +00:00
$a = 100;
$b = 1000;
echo $a <=> $a; // 0 since they are equal
echo $a <=> $b; // -1 since $a < $b
echo $b <=> $a; // 1 since $b > $a
2013-06-29 21:34:54 +00:00
// Variables can be converted between types, depending on their usage.
2013-06-27 16:49:03 +00:00
2013-06-27 09:42:07 +00:00
$integer = 1;
2013-06-29 21:34:54 +00:00
echo $integer + $integer; // => 2
2013-06-27 09:42:07 +00:00
$string = '1';
2013-06-29 21:34:54 +00:00
echo $string + $string; // => 2 (strings are coerced to integers)
2013-06-27 09:42:07 +00:00
$string = 'one';
2013-06-29 21:34:54 +00:00
echo $string + $string; // => 0
2013-06-27 16:49:03 +00:00
// Outputs 0 because the + operator cannot cast the string 'one' to a number
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
// Type casting can be used to treat a variable as another type
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
$boolean = (boolean) 1; // => true
2013-06-27 09:42:07 +00:00
$zero = 0;
2013-06-29 21:34:54 +00:00
$boolean = (boolean) $zero; // => false
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
// There are also dedicated functions for casting most types
2013-06-27 09:42:07 +00:00
$integer = 5;
2013-06-27 16:49:03 +00:00
$string = strval($integer);
2013-06-27 09:42:07 +00:00
$var = null; // Null value
2013-06-29 21:34:54 +00:00
/********************************
* Control Structures
*/
2013-06-27 16:49:03 +00:00
2013-06-29 21:34:54 +00:00
if (true) {
print 'I get printed';
2013-06-27 09:42:07 +00:00
}
2013-06-29 21:34:54 +00:00
if (false) {
2013-06-30 03:25:21 +00:00
print 'I don\'t';
2013-06-27 09:42:07 +00:00
} else {
2013-06-29 21:34:54 +00:00
print 'I get printed';
2013-06-27 09:42:07 +00:00
}
2013-06-29 21:34:54 +00:00
if (false) {
print 'Does not get printed';
} elseif(true) {
print 'Does';
2013-06-27 09:42:07 +00:00
}
2013-07-03 11:31:09 +00:00
// ternary operator
print (false ? 'Does not get printed' : 'Does');
2015-10-02 16:24:45 +00:00
// ternary shortcut operator since PHP 5.3
// equivalent of "$x ? $x : 'Does'""
$x = false;
print($x ?: 'Does');
// null coalesce operator since php 7
$a = null;
$b = 'Does print';
echo $a ?? 'a is not set'; // prints 'a is not set'
echo $b ?? 'b is not set'; // prints 'Does print'
2013-06-29 21:34:54 +00:00
$x = 0;
if ($x === '0') {
print 'Does not print';
} elseif($x == '1') {
print 'Does not print';
2013-06-27 09:42:07 +00:00
} else {
2013-06-29 21:34:54 +00:00
print 'Does print';
2013-06-27 09:42:07 +00:00
}
2013-06-29 21:34:54 +00:00
2013-07-03 11:31:09 +00:00
2013-06-29 21:34:54 +00:00
// This alternative syntax is useful for templates:
2013-06-27 16:49:03 +00:00
?>
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
<?php if ($x): ?>
2013-06-27 20:57:52 +00:00
This is displayed if the test is truthy.
2013-06-27 09:42:07 +00:00
<?php else: ?>
2013-06-27 20:57:52 +00:00
This is displayed otherwise.
2013-06-27 09:42:07 +00:00
<?php endif; ?>
2013-06-27 16:49:03 +00:00
<?php
2013-06-29 21:34:54 +00:00
// Use switch to save some logic.
switch ($x) {
case '0':
print 'Switch does type coercion';
break; // You must include a break, or you will fall through
// to cases 'two' and 'three'
2013-06-27 09:42:07 +00:00
case 'two':
case 'three':
2013-06-27 16:49:03 +00:00
// Do something if $variable is either 'two' or 'three'
2013-06-27 09:42:07 +00:00
break;
default:
2013-06-27 16:49:03 +00:00
// Do something by default
2013-06-27 09:42:07 +00:00
}
2013-06-29 21:34:54 +00:00
// While, do...while and for loops are probably familiar
2013-06-27 09:42:07 +00:00
$i = 0;
while ($i < 5) {
2013-06-27 16:49:03 +00:00
echo $i++;
2013-06-29 21:34:54 +00:00
}; // Prints "01234"
echo "\n";
2013-06-27 09:42:07 +00:00
$i = 0;
do {
2013-06-27 16:49:03 +00:00
echo $i++;
2013-06-29 21:34:54 +00:00
} while ($i < 5); // Prints "01234"
echo "\n";
2013-06-27 09:42:07 +00:00
for ($x = 0; $x < 10; $x++) {
2013-06-30 03:25:21 +00:00
echo $x;
} // Prints "0123456789"
2013-06-29 21:34:54 +00:00
echo "\n";
$wheels = ['bicycle' => 2, 'car' => 4];
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
// Foreach loops can iterate over arrays
2013-06-30 03:25:21 +00:00
foreach ($wheels as $wheel_count) {
echo $wheel_count;
2013-06-29 21:34:54 +00:00
} // Prints "24"
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
echo "\n";
// You can iterate over the keys as well as the values
2013-06-27 09:42:07 +00:00
foreach ($wheels as $vehicle => $wheel_count) {
2013-06-27 16:49:03 +00:00
echo "A $vehicle has $wheel_count wheels";
2013-06-27 09:42:07 +00:00
}
2013-06-29 21:34:54 +00:00
echo "\n";
2013-06-27 09:42:07 +00:00
$i = 0;
while ($i < 5) {
2013-06-29 21:34:54 +00:00
if ($i === 3) {
break; // Exit out of the while loop
2013-06-27 09:42:07 +00:00
}
2013-06-27 16:49:03 +00:00
echo $i++;
2013-06-30 03:25:21 +00:00
} // Prints "012"
2013-06-27 09:42:07 +00:00
2013-06-30 03:25:21 +00:00
for ($i = 0; $i < 5; $i++) {
2013-06-29 21:34:54 +00:00
if ($i === 3) {
2013-06-27 16:49:03 +00:00
continue; // Skip this iteration of the loop
2013-06-27 09:42:07 +00:00
}
2013-06-29 21:34:54 +00:00
echo $i;
} // Prints "0124"
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
/********************************
* Functions
*/
2013-06-27 16:49:03 +00:00
2013-06-29 21:34:54 +00:00
// Define a function with "function":
2013-06-30 03:25:21 +00:00
function my_function () {
2015-10-17 01:43:47 +00:00
return 'Hello';
2013-06-27 09:42:07 +00:00
}
2013-06-29 21:34:54 +00:00
echo my_function(); // => "Hello"
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
// A valid function name starts with a letter or underscore, followed by any
// number of letters, numbers, or underscores.
2013-06-27 09:42:07 +00:00
2013-06-30 03:25:21 +00:00
function add ($x, $y = 1) { // $y is optional and defaults to 1
2015-10-17 01:43:47 +00:00
$result = $x + $y;
return $result;
2013-06-27 09:42:07 +00:00
}
2013-06-29 21:34:54 +00:00
echo add(4); // => 5
echo add(4, 2); // => 6
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
// $result is not accessible outside the function
// print $result; // Gives a warning.
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
// Since PHP 5.3 you can declare anonymous functions;
2013-06-30 03:25:21 +00:00
$inc = function ($x) {
2015-10-17 01:43:47 +00:00
return $x + 1;
2013-06-29 21:34:54 +00:00
};
echo $inc(2); // => 3
2013-06-27 21:11:27 +00:00
function foo ($x, $y, $z) {
2015-10-17 01:43:47 +00:00
echo "$x - $y - $z";
2013-06-27 21:11:27 +00:00
}
2013-06-29 21:34:54 +00:00
// Functions can return functions
2013-06-27 21:11:27 +00:00
function bar ($x, $y) {
2015-10-17 01:43:47 +00:00
// Use 'use' to bring in outside variables
return function ($z) use ($x, $y) {
foo($x, $y, $z);
};
2013-06-27 21:11:27 +00:00
}
$bar = bar('A', 'B');
2013-06-30 03:25:21 +00:00
$bar('C'); // Prints "A - B - C"
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
// You can call named functions using strings
$function_name = 'add';
echo $function_name(1, 2); // => 3
2013-06-30 03:25:21 +00:00
// Useful for programatically determining which function to run.
// Or, use call_user_func(callable $callback [, $parameter [, ... ]]);
// You can get the all the parameters passed to a function
function parameters() {
2015-10-17 01:43:47 +00:00
$numargs = func_num_args();
if ($numargs > 0) {
echo func_get_arg(0) . ' | ';
}
$args_array = func_get_args();
foreach ($args_array as $key => $arg) {
echo $key . ' - ' . $arg . ' | ';
}
}
parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World |
// Since PHP 5.6 you can get a variable number of arguments
function variable($word, ...$list) {
echo $word . " || ";
foreach ($list as $item) {
echo $item . ' | ';
}
}
2015-10-18 22:47:42 +00:00
variable("Separate", "Hello", "World") // Separate || Hello | World |
/********************************
* Includes
*/
<?php
// PHP within included files must also begin with a PHP open tag.
include 'my-file.php';
// The code in my-file.php is now available in the current scope.
// If the file cannot be included (e.g. file not found), a warning is emitted.
include_once 'my-file.php';
// If the code in my-file.php has been included elsewhere, it will
// not be included again. This prevents multiple class declaration errors
require 'my-file.php';
require_once 'my-file.php';
// Same as include(), except require() will cause a fatal error if the
// file cannot be included.
// Contents of my-include.php:
<?php
return 'Anything you like.';
// End file
// Includes and requires may also return a value.
$value = include 'my-include.php';
// Files are included based on the file path given or, if none is given,
// the include_path configuration directive. If the file isn't found in
// the include_path, include will finally check in the calling script's
// own directory and the current working directory before failing.
/* */
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
/********************************
* Classes
*/
2013-06-27 09:42:07 +00:00
2013-06-30 03:25:21 +00:00
// Classes are defined with the class keyword
class MyClass
{
const MY_CONST = 'value'; // A constant
static $staticVar = 'static';
2013-06-27 16:49:03 +00:00
// Static variables and their visibility
public static $publicStaticVar = 'publicStatic';
2013-09-08 20:31:46 +00:00
// Accessible within the class only
private static $privateStaticVar = 'privateStatic';
// Accessible from the class and subclasses
protected static $protectedStaticVar = 'protectedStatic';
2013-06-30 03:25:21 +00:00
// Properties must declare their visibility
public $property = 'public';
2013-06-29 21:34:54 +00:00
public $instanceProp;
protected $prot = 'protected'; // Accessible from the class and subclasses
private $priv = 'private'; // Accessible within the class only
2013-06-29 21:34:54 +00:00
// Create a constructor with __construct
2013-06-30 03:25:21 +00:00
public function __construct($instanceProp) {
2013-06-29 21:34:54 +00:00
// Access instance variables with $this
$this->instanceProp = $instanceProp;
}
2013-06-30 03:25:21 +00:00
2013-06-29 21:34:54 +00:00
// Methods are declared as functions inside a class
2013-06-30 03:25:21 +00:00
public function myMethod()
{
print 'MyClass';
2013-06-27 09:42:07 +00:00
}
2013-09-08 20:31:46 +00:00
//final keyword would make a function unoverridable
2013-06-30 03:25:21 +00:00
final function youCannotOverrideMe()
{
2013-06-27 09:42:07 +00:00
}
/*
2013-09-08 20:31:46 +00:00
* Declaring class properties or methods as static makes them accessible without
* needing an instantiation of the class. A property declared as static can not
* be accessed with an instantiated class object (though a static method can).
2015-10-01 23:42:51 +00:00
*/
2013-06-30 03:25:21 +00:00
public static function myStaticMethod()
{
print 'I am static';
2013-06-27 09:42:07 +00:00
}
}
2015-10-08 03:11:24 +00:00
// Class constants can always be accessed statically
2013-06-30 03:25:21 +00:00
echo MyClass::MY_CONST; // Outputs 'value';
2013-06-30 03:25:21 +00:00
echo MyClass::$staticVar; // Outputs 'static';
MyClass::myStaticMethod(); // Outputs 'I am static';
2013-06-27 09:42:07 +00:00
// Instantiate classes using new
$my_class = new MyClass('An instance property');
// The parentheses are optional if not passing in an argument.
2013-06-30 03:25:21 +00:00
// Access class members using ->
echo $my_class->property; // => "public"
2013-06-29 21:34:54 +00:00
echo $my_class->instanceProp; // => "An instance property"
2013-06-30 03:25:21 +00:00
$my_class->myMethod(); // => "MyClass"
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
// Extend classes using "extends"
2013-06-30 03:25:21 +00:00
class MyOtherClass extends MyClass
{
function printProtectedProperty()
{
echo $this->prot;
2013-06-29 21:34:54 +00:00
}
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
// Override a method
2013-06-30 03:25:21 +00:00
function myMethod()
{
2013-06-29 21:34:54 +00:00
parent::myMethod();
2013-06-30 03:25:21 +00:00
print ' > MyOtherClass';
2013-06-29 21:34:54 +00:00
}
}
2013-06-27 09:42:07 +00:00
2013-06-30 03:25:21 +00:00
$my_other_class = new MyOtherClass('Instance prop');
2013-06-29 21:34:54 +00:00
$my_other_class->printProtectedProperty(); // => Prints "protected"
2013-06-30 03:25:21 +00:00
$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass"
2013-06-27 16:49:03 +00:00
2013-06-30 03:25:21 +00:00
final class YouCannotExtendMe
{
2013-06-29 21:34:54 +00:00
}
// You can use "magic methods" to create getters and setters
2013-06-30 03:25:21 +00:00
class MyMapClass
{
2013-06-27 16:49:03 +00:00
private $property;
2013-06-27 09:42:07 +00:00
public function __get($key)
{
2013-06-27 16:49:03 +00:00
return $this->$key;
2013-06-27 09:42:07 +00:00
}
2013-06-27 09:42:07 +00:00
public function __set($key, $value)
{
2013-06-27 16:49:03 +00:00
$this->$key = $value;
2013-06-27 09:42:07 +00:00
}
}
2013-06-29 21:34:54 +00:00
$x = new MyMapClass();
2013-06-27 16:49:03 +00:00
echo $x->property; // Will use the __get() method
$x->property = 'Something'; // Will use the __set() method
2013-06-27 09:42:07 +00:00
2013-06-29 21:34:54 +00:00
// Classes can be abstract (using the abstract keyword) or
// implement interfaces (using the implements keyword).
// An interface is declared with the interface keyword.
2013-06-27 16:49:03 +00:00
2013-06-27 09:42:07 +00:00
interface InterfaceOne
{
2013-06-27 16:49:03 +00:00
public function doSomething();
2013-06-27 09:42:07 +00:00
}
interface InterfaceTwo
{
2013-06-29 21:34:54 +00:00
public function doSomethingElse();
2013-06-27 09:42:07 +00:00
}
2013-07-08 10:41:14 +00:00
// interfaces can be extended
interface InterfaceThree extends InterfaceTwo
{
public function doAnotherContract();
}
2013-06-27 09:42:07 +00:00
abstract class MyAbstractClass implements InterfaceOne
{
2013-06-30 03:25:21 +00:00
public $x = 'doSomething';
2013-06-27 09:42:07 +00:00
}
2013-06-29 21:34:54 +00:00
class MyConcreteClass extends MyAbstractClass implements InterfaceTwo
2013-06-27 09:42:07 +00:00
{
2013-06-30 03:25:21 +00:00
public function doSomething()
{
2013-06-29 21:34:54 +00:00
echo $x;
}
2013-06-30 03:25:21 +00:00
public function doSomethingElse()
{
echo 'doSomethingElse';
2013-06-29 21:34:54 +00:00
}
2013-06-27 09:42:07 +00:00
}
2013-06-29 21:34:54 +00:00
2013-06-27 09:42:07 +00:00
// Classes can implement more than one interface
class SomeOtherClass implements InterfaceOne, InterfaceTwo
{
2013-06-30 03:25:21 +00:00
public function doSomething()
{
echo 'doSomething';
2013-06-29 21:34:54 +00:00
}
2013-06-30 03:25:21 +00:00
public function doSomethingElse()
{
echo 'doSomethingElse';
2013-06-29 21:34:54 +00:00
}
2013-06-27 09:42:07 +00:00
}
2013-06-29 21:34:54 +00:00
/********************************
* Traits
*/
2013-06-27 09:42:07 +00:00
// Traits are available from PHP 5.4.0 and are declared using "trait"
2013-06-29 21:34:54 +00:00
2013-06-30 03:25:21 +00:00
trait MyTrait
{
2013-06-29 21:34:54 +00:00
public function myTraitMethod()
{
2013-06-30 03:25:21 +00:00
print 'I have MyTrait';
2013-06-29 21:34:54 +00:00
}
}
class MyTraitfulClass
{
use MyTrait;
}
$cls = new MyTraitfulClass();
$cls->myTraitMethod(); // Prints "I have MyTrait"
/********************************
* Namespaces
*/
// This section is separate, because a namespace declaration
// must be the first statement in a file. Let's pretend that is not the case
2013-06-27 16:49:03 +00:00
<?php
2013-06-29 21:34:54 +00:00
// By default, classes exist in the global namespace, and can
// be explicitly called with a backslash.
2013-06-27 09:42:07 +00:00
$cls = new \MyClass();
2013-06-27 16:49:03 +00:00
2013-06-29 21:34:54 +00:00
// Set the namespace for a file
2013-06-27 09:42:07 +00:00
namespace My\Namespace;
class MyClass
{
}
2013-06-29 21:34:54 +00:00
// (from another file)
2013-06-27 09:42:07 +00:00
$cls = new My\Namespace\MyClass;
2013-06-27 16:49:03 +00:00
2013-06-29 21:34:54 +00:00
//Or from within another namespace.
2013-06-27 09:42:07 +00:00
namespace My\Other\Namespace;
use My\Namespace\MyClass;
$cls = new MyClass();
2013-06-29 21:34:54 +00:00
// Or you can alias the namespace;
2013-06-27 16:49:03 +00:00
2013-06-27 09:42:07 +00:00
namespace My\Other\Namespace;
use My\Namespace as SomeOtherNamespace;
$cls = new SomeOtherNamespace\MyClass();
2013-06-27 16:49:03 +00:00
/**********************
* Late Static Binding
*
* /
class ParentClass {
public static function who() {
echo "I'm a " . __CLASS__ . "\n";
}
public static function test() {
// self references the class the method is defined within
self::who();
// static references the class the method was invoked on
static::who();
}
}
ParentClass::test();
/*
I'm a ParentClass
I'm a ParentClass
*/
class ChildClass extends ParentClass {
public static function who() {
echo "But I'm " . __CLASS__ . "\n";
}
}
ChildClass::test();
/*
I'm a ParentClass
But I'm ChildClass
*/
2015-10-07 08:01:09 +00:00
/**********************
* Error Handling
*
2013-06-29 21:34:54 +00:00
*/
2013-06-27 09:42:07 +00:00
2015-10-07 07:12:31 +00:00
// Simple error handling can be done with try catch block
try {
// Do something
2015-10-15 20:28:38 +00:00
} catch (Exception $e) {
2015-10-07 07:12:31 +00:00
// Handle exception
}
// When using try catch blocks in a namespaced enviroment use the following
try {
2015-10-07 07:12:31 +00:00
// Do something
} catch (\Exception $e) {
2015-10-07 07:12:31 +00:00
// Handle exception
}
// Custom exceptions
class MyException extends Exception {}
try {
$condition = true;
2015-10-07 07:12:31 +00:00
if ($condition) {
throw new MyException('Something just happend');
}
2015-10-07 07:12:31 +00:00
} catch (MyException $e) {
// Handle my exception
}
2013-06-27 09:42:07 +00:00
```
## More Information
2013-09-08 20:31:46 +00:00
Visit the [official PHP documentation](http://www.php.net/manual/) for reference
and community input.
2013-06-27 09:42:07 +00:00
2013-09-08 20:31:46 +00:00
If you're interested in up-to-date best practices, visit
[PHP The Right Way](http://www.phptherightway.com/).
2013-06-27 09:42:07 +00:00
2013-09-08 20:31:46 +00:00
If you're coming from a language with good package management, check out
[Composer](http://getcomposer.org/).
2013-06-30 03:25:21 +00:00
2013-09-08 20:31:46 +00:00
For common standards, visit the PHP Framework Interoperability Group's
2015-10-07 07:12:31 +00:00
[PSR standards](https://github.com/php-fig/fig-standards).