PHP: Hypertext Preprocessor
Runs on the server, not in the browser
With PHP you are not limited to output HTML. You can output images or PDF files. You can also output any text, such as XHTML and XML.
Install:
dnf install php
<?php
declare(strict_types=1);
echo "Hello, PHP\n";
$name = 'Master';
$age = 21;
$iStudent = true;
$int1 = 012; // => 10 (a leading 0 denotes an octal number)
$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal)
$int5 = 0b11111111; // 255 (a leading 0b denotes a binary number)
$float = 1.234;
$float = 1.2e3;
$float = 7E-10;
// Delete variable
unset($int1);
$number += 1; // Shorthand op
echo $number++; // increment op
// Special characters are only escaped in double quotes
$escaped = "This contains a \t tab character.";
echo "Age check\n";
if ($age >= 18) {
echo "Adult\n";
} else {
echo "Minor\n";
}
for ($i = 0; $i < 5; $i++) {
echo $i;
}
echo "\n";
function add(int $a, int $b): int {
return $a + $b;
}
echo add(30, 45), "\n";
$nums = [1,2,3,4];
$user = [
"name" => "Master",
"role" => "student"
];
class User {
public function __construct(
public string $name,
public string $role
) {}
}
$user = new User("Master", "Student");
echo $user->name;
echo "\n";
// Single line comment
# single line comment
/*
Mulit line comment*/
var_dump(5);
var_dump("John");
var_dump(3.14);
var_dump(true);
?>
- PHP script starts with
<?phpand ends with?>
php basic.php To run a file
php -S web.php To start php server
PHP keywords (e.g. if, else, echo, etc.), classes, functions, and user-defined functions are case-insensitive.
Variable name must start with letter or underscore letter. Can only contain alphanumeric and underscore. Variables are case sensitive.
PHP has three different variable scopes:
global - Variable declared outside function has global scope and can only be accessed outside function
local - Variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.
static - Still local to that function, but its value persist when function is recalled
function myTest() {
static $x = 0; // static scope
echo $x;
$x++;
}
- global keyword can be used to access global variables inside function.
function myTest() {
global $x, $y;
$y = $x + $y;
}
// GLOBALS array store all global vars
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}