Summary: Learning about variable scopes, escaping characters, strict types, dates, ad operations, interaction and connecting MySQL to PHP using PDO.
Variable Scopes
There are two types of scopes in the PHP
global and local. The global scope variables are accessible from anywhere form the PHP
script. And the local variables are only accessible at there local scopes.
Examples:
// Global
<?php
$x = 5; // global scope
Found
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
If we want to access global variable inside a function we can use the global
keyword. To do this, use the global
keyword before the variables (inside the function):
// Local
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
// Using global variable in function
$x = 5;
function myTest() {
global $x
echo "<p>$x</p>";
}
myTest();
Rare Cases
Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job. To do this, use the static
keyword when you first declare the variable:
Example
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
/* output
0
1
2
*/
PHP echo and print Statements
echo
and print
are more or less the same. They are both used to output data to the screen. The differences are small: echo
has no return value while print
has a return value of 1 so it can be used in expressions. echo
can take multiple parameters (although such usage is rare) while print
can take one argument. echo
is marginally faster than print
.
<?php
echo "Hello World";
print "Hello World";
// same output
?>
Rare string operations
If we wanted to split the whole string into array of chars we can use str_split
function
<?php
$str = "Hello Friend";
$arr1 = str_split($str);
$arr2 = str_split($str, 3);
print_r($arr1);
print_r($arr2);
?>
The above example will output:
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
[5] =>
[6] => F
[7] => r
[8] => i
[9] => e
[10] => n
[11] => d
)
Array
(
[0] => Hel
[1] => lo
[2] => Fri
[3] => end
)
Escape character
We can use the escape character \
to escape for example quotes.
$x = "We are the so-called \"Vikings\" from the north.";
Array operations
Foreach by ref
When looping through the array items, any changes done to the array item will, by default, NOT affect the original array:
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
if ($x == "blue") $x = "pink";
}
var_dump($colors);
BUT, by using the &
character in the foreach
declaration, the array item is assigned by reference, which results in any changes done to the array item will also be done to the original array:
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as &$x) {
if ($x == "blue") $x = "pink";
}
var_dump($colors);
To specify strict
we need to set declare(strict_types=1);
. This must be on the very first line of the PHP file.
Strict types
To add strict type checking we can use the declare(strict_types=1)
.
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : int {
return (int)($a + $b);
}
echo addNumbers(1.2, 5.2);
Date basics
- d – Represents the day of the month (01 to 31)
- m – Represents a month (01 to 12)
- Y – Represents a year (in four digits)
- l (lowercase ‘L’) – Represents the day of the week
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
Make date
mktime(hour, minute, second, month, day, year)
The example below creates a date and time with the date()
function from a number of parameters in the mktime()
function:
<?php
$d=mktime(11, 14, 54, 8, 12, 2014);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
Interacting with files
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
The file may be opened in one of the following modes:
Modes | Description |
---|---|
r | Open a file for read only. File pointer starts at the beginning of the file |
w | Open a file for write only. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file |
a | Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist |
x | Creates a new file for write only. Returns FALSE and an error if file already exists |
r+ | Open a file for read/write. File pointer starts at the beginning of the file |
w+ | Open a file for read/write. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file |
a+ | Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist |
x+ | Creates a new file for read/write. Returns FALSE and an error if file already exists |
PHP Create/Retrieve a Cookie
The following example creates a cookie named “user” with the value “John Doe”. The cookie will expire after 30 days (86400 * 30). The “/” means that the cookie is available in entire website (otherwise, select the directory you prefer).
We then retrieve the value of the cookie “user” (using the global variable $_COOKIE). We also use the isset()
function to find out if the cookie is set:
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Note: The setcookie()
function must appear BEFORE the <html> tag.
Working with json
The json_decode() function returns an object by default. The json_decode() function has a second parameter, and when set to true, JSON objects are decoded into associative arrays.
This example decodes JSON data into a PHP associative array:
<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
var_dump(json_decode($jsonobj, true));
PHP – The final Keyword
The final
keyword can be used to prevent class inheritance or to prevent method overriding.
The following example shows how to prevent class inheritance:
<?php
final class Fruit {
// some code
}
// will result in error
class Strawberry extends Fruit {
// some code
}
?>
The following example shows how to prevent method overriding:
<?php
class Fruit {
final public function intro() {
// some code
}
}
class Strawberry extends Fruit {
// will result in error
public function intro() {
// some code
}
}
?>
PHP – What are Traits?
PHP only supports single inheritance: a child class can inherit only from one single parent. So, what if a class needs to inherit multiple behaviors? OOP traits solve this problem. Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected). Traits are declared with the trait
keyword:
<?php
trait TraitName {
// some code...
}
?>
To use a trait in a class, use the use
keyword:
<?php
class MyClass {
use TraitName;
}
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Working with database
Database connection PDO
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Transactions using PDO
// begin the transaction
$conn->beginTransaction();
// our SQL statements
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')");
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com')");
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')");
// commit the transaction
$conn->commit();
Using prepared statement in PDO
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
ref: https://www.w3schools.com/php/default.asp
Leave a Reply