mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-11-24 06:53:08 +03:00
12 KiB
12 KiB
language | author | author_url |
---|---|---|
php | Malcolm Fell | http://emarref.net/ |
This document describes PHP 5+.
<?php // PHP code must be enclosed with <?php ? > tags
// 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.
*/
// Use "echo" or "print" to print output
print('Hello '); // Prints "Hello " with no line break
// () are optional for print and echo
echo 'World\n'; // Prints "World" with a line break
// (all statements must end with a semicolon)
// Anything outside <?php tags is echoed automatically
?>Hello World Again!
<?php
/************************************
* 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.
// Boolean values are case-insensitive
$boolean = true; // or TRUE or True
$boolean = false; // or FALSE or False
// Integers
$int1 = 19; // => 19
$int2 = -19; // => -19
$int3 = 019; // => 15 (a leading 0 denotes an octal number)
$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal)
// Floats (aka doubles)
$float = 1.234;
$float = 1.2e3;
$float = 7E-10;
// Arithmetic
$sum = 1 + 1; // 2
$difference = 2 - 1; // 1
$product = 2 * 2; // 4
$quotient = 2 / 1; // 2
// Shorthand arithmetic
$number = 0;
$number += 1; // Add 1 to $number
echo $number++; // Prints 1 (increments after evaluation)
echo ++$number; // Prints 3 (increments before evalutation)
$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'
// Special characters are only escaped in double quotes
$escaped = "This contains a \t tab character.";
$unescaped = 'This just contains a slash and a t: \t';
// Enclose a variable in curly braces if needed
$money = "I have $${number} in the bank.";
// Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners
$nowdoc = <<<'END'
Multi line
string
END;
// Heredocs will do string interpolation
$heredoc = <<<END
Multi line
$sgl_quotes
END;
// String concatenation is done with .
echo 'This string ' . 'is concatenated';
/********************************
* Arrays
*/
// All arrays in PHP are associative arrays (hashmaps),
// Associative arrays, known as hashmaps in some languages.
// Works with all PHP versions
$associative = array('One' => 1, 'Two' => 2, 'Three' => 3);
// PHP 5.4 introduced a new syntax
$associative = ['One' => 1, 'Two' => 2, 'Three' => 3];
echo $associative['One']; // prints "1"
// List literals implicitly assign integer keys
$array = ['One', 'Two', 'Three'];
echo $array[0]; // => "One"
/********************************
* Output
*/
echo('Hello World!');
// Prints Hello World! to stdout.
// Stdout is the web page if running in a browser.
print('Hello World!'); // The same as echo
// echo is actually a language construct, so you can drop the parentheses.
echo 'Hello World!';
print 'Hello World!'; // So is print
$paragraph = 'paragraph';
echo 100;
echo $paragraph;
// If short open tags are configured, or your PHP version is
// 5.4.0 or greater, you can use the short echo syntax
?>
<p><?= $paragraph ?></p>
<?php
$x = 1;
$y = 2;
$x = $y; // A now contains the same value sa $y
$z = &$y;
// $x now contains a reference to $y. Changing the value of
// $x will change the value of $y also, and vice-versa.
echo $x; // => 2
echo $z; // => 2
$y = 0;
echo $x; // => 2
echo $z; // => 0
/********************************
* Logic
*/
$a = 0;
$b = '0';
$c = '1';
$d = '1';
// assert throws a warning if its argument is not true
// These comparisons will always be true, even if the types aren't the same.
assert($a == $b); // equality
assert($b != $a); // inequality
assert($a <> $b); // alternative inequality
assert($a < $c);
assert($c > $b);
assert($a <= $b);
assert($c >= $d);
// The following will only be true if the values match and are the same type.
assert($c === $d);
assert($a !== $d);
assert(1 == '1');
assert(1 !== '1');
// Variables can be converted between types, depending on their usage.
$integer = 1;
echo $integer + $integer; // => 2
$string = '1';
echo $string + $string; // => 2 (strings are coerced to integers)
$string = 'one';
echo $string + $string; // => 0
// Outputs 0 because the + operator cannot cast the string 'one' to a number
// Type casting can be used to treat a variable as another type
$boolean = (boolean) 1; // => true
$zero = 0;
$boolean = (boolean) $zero; // => false
// There are also dedicated functions for casting most types
$integer = 5;
$string = strval($integer);
$var = null; // Null value
/********************************
* Control Structures
*/
if (true) {
print 'I get printed';
}
if (false) {
print "I don't";
} else {
print 'I get printed';
}
if (false) {
print 'Does not get printed';
} elseif(true) {
print 'Does';
}
$x = 0;
if ($x === '0') {
print 'Does not print';
} elseif($x == '1') {
print 'Does not print';
} else {
print 'Does print';
}
// This alternative syntax is useful for templates:
?>
<?php if ($x): ?>
This is displayed if the test is truthy.
<?php else: ?>
This is displayed otherwise.
<?php endif; ?>
<?php
// 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
case 'two':
case 'three':
// Do something if $variable is either 'two' or 'three'
break;
default:
// Do something by default
}
// While, do...while and for loops are probably familiar
$i = 0;
while ($i < 5) {
echo $i++;
}; // Prints "01234"
echo "\n";
$i = 0;
do {
echo $i++;
} while ($i < 5); // Prints "01234"
echo "\n";
for ($x = 0; $x < 10; $x++) {
echo $x; // Will echo 0 - 9
}// Prints "0123456789"
echo "\n";
$wheels = ['bicycle' => 2, 'car' => 4];
// Foreach loops can iterate over arrays
foreach ($wheels as $wheel_count){
echo "$wheel_count";
} // Prints "24"
echo "\n";
// You can iterate over the keys as well as the values
foreach ($wheels as $vehicle => $wheel_count) {
echo "A $vehicle has $wheel_count wheels";
}
echo "\n";
$i = 0;
while ($i < 5) {
if ($i === 3) {
break; // Exit out of the while loop
}
echo $i++;
}// Prints "012"
for($i = 0; $i < 5; $i++){
if ($i === 3) {
continue; // Skip this iteration of the loop
}
echo $i;
} // Prints "0124"
/********************************
* Functions
*/
// Define a function with "function":
function my_function() {
return 'Hello';
}
echo my_function(); // => "Hello"
// A valid function name starts with a letter or underscore, followed by any
// number of letters, numbers, or underscores.
function add($x, $y = 1) { // $y is optional, and defaults to 2
$result = $x + $y;
return $result;
}
echo add(4); // => 5
echo add(4, 2); // => 6
// $result is not accessible outside the function
// print $result; // Gives a warning.
// Since PHP 5.3 you can declare anonymous functions;
$inc = function($x){
return $x + 1;
};
echo $inc(2); // => 3
function foo ($x, $y, $z) {
echo "$x - $y - $z";
}
// Functions can return functions
function bar ($x, $y) {
// Use 'use' to bring in outside variables
return function ($z) use ($x, $y) {
foo($x, $y, $z);
};
}
$bar = bar('A', 'B');
$bar('C');
// You can call named functions using strings
$function_name = 'add';
echo $function_name(1, 2); // => 3
// But, you should probably use anonymous functions instead.
/********************************
* Classes
*/
//Classes are defined with the class keyword
class MyClass {
const MY_CONST = 'value'; // A constant
static $staticVar = 'static';
public $property = 'public'; // Properties must declare their visibility
private $privprop = 'private'; // Accessible within the class only
protected $protprop = 'protected'; // Accessible within the class and subclasses
public $instanceProp;
// Create a constructor with __construct
public function __construct($instanceProp){
// Access instance variables with $this
$this->instanceProp = $instanceProp;
}
// Methods are declared as functions inside a class
public function myMethod() {
print "MyClass";
}
final function youCannotOverrideMe() {
}
public static function myStaticMethod() {
print "I am static";
}
}
echo MyClass::MY_CONST; // Outputs "value";
echo MyClass::$staticVar; // Outputs 'static';
MyClass::myStaticMethod(); // Outputs "I am static";
// Access class members using ->.
$my_class = new MyClass("An instance property"); // The parentheses are optional.
echo $my_class->property; // => "public"
echo $my_class->instanceProp; // => "An instance property"
$my_class->myMethod(); // => "MyClass"
// Extend classes using "extends"
class MyOtherClass extends MyClass{
function printProtectedProperty(){
echo $this->protprop;
}
// Override a method
function myMethod() {
parent::myMethod();
print " > MyOtherClass";
}
}
$my_other_class = new MyOtherClass("Instance prop");
$my_other_class->printProtectedProperty(); // => Prints "protected"
$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass"
final class YouCannotExtendMe {
}
// You can use "magic methods" to create getters and setters
class MyMapClass {
private $property;
public function __get($key)
{
return $this->$key;
}
public function __set($key, $value)
{
$this->$key = $value;
}
}
$x = new MyMapClass();
echo $x->property; // Will use the __get() method
$x->property = 'Something'; // Will use the __set() method
// Classes can be abstract (using the abstract keyword) or
// implement interfaces (using the implements keyword).
// An interface is declared with the interface keyword.
interface InterfaceOne
{
public function doSomething();
}
interface InterfaceTwo
{
public function doSomethingElse();
}
abstract class MyAbstractClass implements InterfaceOne
{
public $x = "doSomething";
}
class MyConcreteClass extends MyAbstractClass implements InterfaceTwo
{
public function doSomething(){
echo $x;
}
public function doSomethingElse(){
echo "doSomethingElse";
}
}
// Classes can implement more than one interface
class SomeOtherClass implements InterfaceOne, InterfaceTwo
{
public function doSomething(){
echo "doSomething";
}
public function doSomethingElse(){
echo "doSomethingElse";
}
}
/********************************
* Traits
*/
//Traits are available since PHP 5.4.0 and are declared using the trait keyword.
trait MyTrait {
public function myTraitMethod()
{
print "I have MyTrait";
}
}
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
/*
<?php
// By default, classes exist in the global namespace, and can
// be explicitly called with a backslash.
$cls = new \MyClass();
// Set the namespace for a file
namespace My\Namespace;
class MyClass
{
}
// (from another file)
$cls = new My\Namespace\MyClass;
//Or from within another namespace.
namespace My\Other\Namespace;
use My\Namespace\MyClass;
$cls = new MyClass();
// Or you can alias the namespace;
namespace My\Other\Namespace;
use My\Namespace as SomeOtherNamespace;
$cls = new SomeOtherNamespace\MyClass();
*/
More Information
Visit the official PHP documentation for reference and community input.
If you're interested in up-to-date best practices, visit PHP The Right Way.
If you're coming from a language with good package management, check out Composer.