Initial commit

parents
Showing with 1333 additions and 0 deletions
## Example files for the title:
# Up to Speed with PHP 7, by David Powers
[![Up to Speed with PHP 7, by David Powers](http://akamaicovers.oreilly.com/images/9781771374910/cat.gif)](https://www.safaribooksonline.com/library/view/title/9781771374910//)
The following applies to example files from material published by O’Reilly Media, Inc. Content from other publishers may include different rules of usage. Please refer to any additional usage rights explained in the actual example files or refer to the publisher’s website.
O'Reilly books are here to help you get your job done. In general, you may use the code in O'Reilly books in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from our books does not require permission. Answering a question by citing our books and quoting example code does not require permission. On the other hand, selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Incorporating a significant amount of example code from our books into your product's documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN.
If you think your use of code examples falls outside fair use or the permission given here, feel free to contact us at <permissions@oreilly.com>.
Please note that the examples are not production code and have not been carefully testing. They are provided "as-is" and come with no warranty of any kind.
{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf350
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww9000\viewh8400\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural
\f0\fs24 \cf0 No work files for this lesson...}
\ No newline at end of file
{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf350
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww9000\viewh8400\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural
\f0\fs24 \cf0 No work files for this lesson...}
\ No newline at end of file
<?php
// Basic division
var_dump(6/3);
var_dump(5/2);
// Find the remainder
//echo 5 % 2;
// Integer division
//echo floor(5/2);
//echo (int) (5/2);
// Initial proposal: new operator
//echo 5 %% 2;
// New function for integer division
//echo intdiv(5, 2);
\ No newline at end of file
<?php
function convertMetersToYards($meters) {
// Convert meters to tenths of a millimeter
$mmx10 = $meters * 10000;
// Divide by 9144 to get yards
$y = intdiv($mmx10, 9144);
// Use modulo division to get the remainder
$f = $mmx10 % 9144;
// Divide by 3048 to get feet
$ft = intdiv($f, 3048);
// Get the remainder and convert to inches
$i = $f % 3048;
$i = number_format($i / 254, 2);
return "$y yards $ft feet $i inches";
}
echo convertMetersToYards(50);
\ No newline at end of file
First name,Family name
John,Doe
David,Smith
Tom,Jones
Angela,Smith
Samantha,Jones
Jane,Doe
<?php
$var = $non_existent ?? 'default';
echo $var;
\ No newline at end of file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Null coalesce operator</title>
</head>
<body>
<form action="nullcoalesce_03.php" method="post">
<p>
<label for="name">Enter your name: </label>
<input type="text" name="name" id="name">
</p>
<p><input type="submit" name="send" value="Submit"></p>
</form>
</body>
</html>
<?php
$name = $_POST['name'] ?: 'guest';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Null coalesce operator</title>
</head>
<body>
<p>Hello, <?= $name; ?></p>
</body>
</html>
<?php
if (isset($_POST['name']) && empty($_POST['name'])) {
unset($_POST['name']);
}
$name = $_POST['name'] ?? 'guest';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Null coalesce operator</title>
</head>
<body>
<p>Hello, <?= $name; ?></p>
</body>
</html>
<?php
echo random_bytes(20);
//echo bin2hex(random_bytes(20));
<?php
$tries = 0;
while (true) {
// Roll two dice
$dice1 = random_int(1, 6);
$dice2 = random_int(1, 6);
echo "$dice1 $dice2<br>";
$tries++;
// End the loop when we get a double six
if ($dice1 == 6 && $dice2 == 6) {
$throws = $tries > 1 ? 'throws' : 'throw';
echo "<p>It took $tries $throws to get a double six";
break;
}
}
\ No newline at end of file
<?php
$list = <<< END
<p class=ListParaFirst><span
style='font-family:Symbol;'>·<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span>APPLES</p>
<p class=ListParaMiddle><span
style='font-family:Symbol;'>·<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span>BANANAS</p>
<p class=ListParaMiddle><span
style='font-family:Symbol;'>·<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span>ORANGES</p>
<p class=ListParaLast><span
style='font-family:Symbol;'>·<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span>PEARS</p>
END;
$list = preg_replace(
array(
'{<p class=ListParaFirst[\s\S]*?</span></span>(\w+)</p>}m',
'{<p class=ListParaMiddle[\s\S]*?</span></span>(\w+)</p>}m',
'{<p class=ListParaLast[\s\S]*?</span></span>(\w+)</p>}m'
),
array(
'<ul>' . PHP_EOL . "<li>$1</li>",
"<li>$1</li>",
"<li>$1</li>" . PHP_EOL . '</ul>'
),
$list
);
echo $list;
\ No newline at end of file
<?php
$list = <<< END
<p class=ListParaFirst><span
style='font-family:Symbol;'>·<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span>APPLES</p>
<p class=ListParaMiddle><span
style='font-family:Symbol;'>·<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span>BANANAS</p>
<p class=ListParaMiddle><span
style='font-family:Symbol;'>·<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span>ORANGES</p>
<p class=ListParaLast><span
style='font-family:Symbol;'>·<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span>PEARS</p>
END;
$list_start = '<ul>';
$list_end = '</ul>';
$item_start = '<li>';
$item_end = '</li>';
// Match the last bullet point, and wrap the text
// in a pair of <li> tags followed by closing </ul>
function lastBullet($m) {
return "<li>$m[1]</li>" . PHP_EOL . '</ul>';
}
$list = preg_replace_callback_array(
array(
// Match the bullet text, change case, and
// replace closing </p> tag with </li>
'{</span>(\w+)</p>}m' => function($m) use ($item_end) {
return ucfirst(strtolower($m[1])) . $item_end;
},
// Match first bullet point, and add opening <ul> and <li> tags
'{<p class=ListParaFirst[\s\S]*?</span>}m' => function($m) use ($list_start, $item_start) {
return $list_start . PHP_EOL . $item_start;
},
// Match middle bullets, and add opening <li> tags
'{<p class=ListParaMiddle[\s\S]*?</span>}m' => function($m) use ($item_start) {
return $item_start;
},
'{<p class=ListParaLast[\s\S]*?</span>(\w+)</li>}m' => 'lastBullet'
), $list
);
echo $list;
\ No newline at end of file
<?php
$a = 5;
$b = $c = 9;
echo '$a = 5, $b and $c = 9 <br>';
echo '$a &lt;=&gt; $b returns ' . ($a <=> $b) . '<br>';
echo '$b &lt;=&gt; $c returns ' . ($b <=> $c) . '<br>';
echo '$c &lt;=&gt; $a returns ' . ($c <=> $a);
<?php
$file = new SplFileObject('names.csv');
// Discard the column headers
$file->getCurrentLine();
// Build a multidimensional array of the remaining lines
while (!$file->eof()) {
$line = $file->fgetcsv();
// Ignore empty lines
if (!is_null($line[0])) {
$names[] = $line;
}
}
// Display the names
foreach ($names as $name) {
echo implode(' ', $name) . '<br>';
}
\ No newline at end of file
<?php
$file = new SplFileObject('names.csv');
// Discard the column headers
$file->getCurrentLine();
// Build a multidimensional array of the remaining lines
while (!$file->eof()) {
$line = $file->fgetcsv();
// Ignore empty lines
if (!is_null($line[0])) {
$names[] = $line;
}
}
usort($names, function($a, $b) {
return [$a[1], $a[0]] <=> [$b[1], $b[0]];
});
// Display the names
foreach ($names as $name) {
echo implode(' ', $name) . '<br>';
}
\ No newline at end of file
<?php
// Four-digit codepoints
echo "<p>Caf\u{00e9} Royal</p>";
//$tel = "\u{260E}";
//echo "<p>$tel (212) 555-0199</p>";
// Five-digit codepoint
//echo "<p>PHP 7 has spaceships! \u{1F680}</p>";
// Leading zeros omitted
//echo "<p>Caf\u{e9} Royal</p>";
// JSON not affected
//echo json_decode("\"\u00e9\"");
\ No newline at end of file
<?php
interface HolidayInterface
{
public function getMemorial() : DateTimeImmutable;
public function getThanksgiving();
}
\ No newline at end of file
<?php
function wordsToUpper($string) {
if (empty($string) || is_null($string)) {
return '';
}
$string = explode(' ', $string);
return array_map('strtoupper', $string);
}
$input = 'one two three';
$converted = wordsToUpper($input);
echo '<pre>';
print_r($converted);
echo '</pre>';
\ No newline at end of file
<?php
function wordsToUpper($string) : array {
if (empty($string) || is_null($string)) {
return [];
}
$string = explode(' ', $string);
return array_map('strtoupper', $string);
}
$input = '';
$converted = wordsToUpper($input);
echo '<pre>';
print_r($converted);
echo '</pre>';
<?php
require_once './HolidayInterface.php';
class Holidays implements HolidayInterface
{
protected $date;
public function __construct($year = null)
{
$y = $year ?? date('Y');
$this->date = new DateTimeImmutable("January 1, $y");
}
public function getMemorial()
{
return $this->date->modify('last Monday of May');
}
public function getThanksgiving()
{
return $this->date->modify('fourth Thursday of November');
}
}
$holidays = new Holidays();
$memorial = $holidays->getMemorial();
echo $memorial->format('l, F j, Y') . '<br>';
$thanksgiving = $holidays->getThanksgiving();
echo $thanksgiving->format('l, F j, Y') . '<br>';
$blackFriday = $thanksgiving->modify('+1 day');
echo $blackFriday->format('l, F j, Y') . '<br>';
\ No newline at end of file
<?php
require_once './HolidayInterface.php';
class Holidays implements HolidayInterface
{
protected $date;
public function __construct($year = null)
{
$y = $year ?? date('Y');
$this->date = new DateTimeImmutable("January 1, $y");
}
public function getMemorial() : DateTimeImmutable
{
return $this->date->modify('last Monday of May');
}
public function getThanksgiving() : DateTimeImmutable
{
return $this->date->modify('fourth Thursday of November');
}
}
$holidays = new Holidays(2016);
$memorial = $holidays->getMemorial();
echo $memorial->format('l, F j, Y') . '<br>';
$thanksgiving = $holidays->getThanksgiving();
echo $thanksgiving->format('l, F j, Y') . '<br>';
$blackFriday = $thanksgiving->modify('+1 day');
echo $blackFriday->format('l, F j, Y') . '<br>';
\ No newline at end of file
<?php
declare(strict_types=1);
function doubleIt(int $value) : int {
return $value * 2;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scalar type hinting</title>
</head>
<body>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
<p><label>Enter an integer: </label>
<input type="number" name="integer">
</p>
<p><input type="submit" name="submit" value="Submit"></p>
</form>
<?php
if (isset($_POST['submit'])) {
echo '<p>Double that number is ' . doubleIt($_POST['integer']) . '</p>';
}
?>
</body>
</html>
\ No newline at end of file
<?php
// Turn on strict mode
declare(strict_types=1);
// Strictly type-checked return values
// Type checking of params depends on calling file
function addIntegers(int $a, int $b) : int {
return $a + $b;
}
function addFloats(float $a, float $b) : float {
return $a + $b;
}
function upperRev(string $a) : string {
return strtoupper(strrev($a));
}
function isItTrue(bool $a) : string {
return $a ? 'true' : 'false';
}
\ No newline at end of file
<?php
// Type checking of params depends on calling file
// Return values will be cast to the specified type
function addIntegers(int $a, int $b) : string {
return $a + $b;
}
function addFloats(float $a, float $b) : int {
return $a + $b;
}
function upperRev(string $a) : float {
return strtoupper(strrev($a));
}
function isItTrue(bool $a) : bool {
return $a ? 'true' : 'false';
}
/*function addIntegers(int $a, int $b) : int {
return $a + $b;
}
function addFloats(float $a, float $b) : float {
return $a + $b;
}
function upperRev(string $a) : string {
return strtoupper(strrev($a));
}
function isItTrue(bool $a) : string {
return $a ? 'true' : 'false';
}*/
<?php
// Turn on strict mode
declare(strict_types=1);
// Strictly type-checked parameters, or are they?
function addIntegers(int $a, int $b) {
return $a + $b;
}
function addFloats(float $a, float $b) {
return $a + $b;
}
function upperRev(string $a) {
return strtoupper(strrev($a));
}
function isItTrue(bool $a) {
return $a ? 'true' : 'false';
}
\ No newline at end of file
<?php
// Weakly type-checked parameters
function addIntegers(int $a, int $b) {
return $a + $b;
}
function addFloats(float $a, float $b) {
return $a + $b;
}
function upperRev(string $a) {
return strtoupper(strrev($a));
}
function isItTrue(bool $a) {
return $a ? 'true' : 'false';
}
\ No newline at end of file
<?php
// Turn on strict mode
declare(strict_types=1);
// Strictly type-checked return values
// The return value must be of the declared type
function getInteger($input) : int {
return $input;
}
function getFloat($input) : float {
return $input;
}
function getString($input) : string {
return $input;
}
function getBoolean($input) : bool {
return $input;
}
<?php
// Weakly type-checked return values
// In weak mode, the return value is cast to the specified type
function getInteger($input) : int {
return $input;
}
function getFloat($input) : float {
return $input;
}
function getString($input) : string {
return $input;
}
function getBoolean($input) : bool {
return $input;
}
<?php
//declare(strict_types=1);
require_once './functions/scalar_both_weak.php';
// Included functions use weak type checks for return value
echo var_dump(addIntegers(4.5, 3.2)) . '<br>';
//echo var_dump(addIntegers(4, 3)) . '<br>';
echo var_dump(addFloats(5, '3.2')) . '<br>';
//echo var_dump(addFloats(5, 3.2)) . '<br>';
echo var_dump(upperRev(12345)) . '<br>';
//echo var_dump(upperRev('Fahrenheit 451')) . '<br>';
echo var_dump(isItTrue(3.6));
//echo var_dump(isItTrue(false));
\ No newline at end of file
<?php
//declare(strict_types=1);
require_once './functions/scalar_both_strict.php';
// Included functions use strict type checks for return value
// Parameter type checking depends on mode in this file
echo var_dump(addIntegers(4.5, 3.2)) . '<br>';
//echo var_dump(addIntegers(4, 3)) . '<br>';
echo var_dump(addFloats(5, '3')) . '<br>';
//echo var_dump(addFloats(5.5, 3)) . '<br>';
echo var_dump(upperRev(12345)) . '<br>';
//echo var_dump(upperRev('Fahrenheit 451')) . '<br>';
echo var_dump(isItTrue(3.6));
//echo var_dump(isItTrue(false));
\ No newline at end of file
<?php
//declare(strict_types=1);
require_once './functions/scalar_params_weak.php';
// Included functions use weak type checks for params
echo var_dump(addIntegers(4.5, 3.4)) . '<br>';
//echo var_dump(addIntegers(4, 3)) . '<br>';
echo var_dump(addFloats(5, '3')) . '<br>';
//echo var_dump(addFloats(5.6, 3)) . '<br>';
echo var_dump(upperRev(12345)) . '<br>';
//echo var_dump(upperRev('4 seasons')) . '<br>';
echo var_dump(isItTrue(3.6));
//echo var_dump(isItTrue(false));
\ No newline at end of file
<?php
//declare(strict_types=1);
require_once './functions/scalar_params_strict.php';
// Included functions use strict type checks for params
echo var_dump(addIntegers(4.5, 3.4)) . '<br>';
//echo var_dump(addIntegers(4, 3)) . '<br>';
echo var_dump(addFloats(5, '3')) . '<br>';
//echo var_dump(addFloats(5.6, 3)) . '<br>';
echo var_dump(upperRev(12345)) . '<br>';
//echo var_dump(upperRev('4 seasons')) . '<br>';
echo var_dump(isItTrue(3.6));
//echo var_dump(isItTrue(false));
\ No newline at end of file
<?php
//declare(strict_types=1);
require_once './functions/scalar_return_weak.php';
// Included functions have weakly type-checked return values
$input = 4.5;
echo var_dump(getInteger($input)) . '<br>';
echo var_dump(getFloat($input)) . '<br>';
echo var_dump(getString($input)) . '<br>';
echo var_dump(getBoolean($input));
\ No newline at end of file
<?php
//declare(strict_types=1);
require_once './functions/scalar_return_strict.php';
// Included functions have strictly type-checked return values
$input = 4.5;
echo var_dump(getInteger($input)) . '<br>';
//$input = 4.5;
echo var_dump(getFloat($input)) . '<br>';
//$input = '4 seasons';
echo var_dump(getString($input)) . '<br>';
//$input = false;
echo var_dump(getBoolean($input));
\ No newline at end of file
<?php
declare(strict_types=1);
function roundedAverage(array $values) : int {
$avg = array_sum($values) / count($values);
return round($avg);
}
function addIntegers(int $a, int $b) : int {
return $a + $b;
}
\ No newline at end of file
<?php
//declare(strict_types=1);
require_once './strict_01.php';
$num = [18.6, 21.2, 16.5];
$avg = roundedAverage($num);
echo $avg . '<br>';
//$total = addIntegers($avg, 12345);
//echo strrev($total);
\ No newline at end of file
<?php
$json = file_get_contents('./sf_bikes.json');
$json = json_decode($json);
<?php
$json = file_get_contents('./sf_bikes.json');
$json = json_decode($json);
$bikeSpaces = new class() extends SplHeap
{
protected function compare($data1, $data2)
{
return (int) $data2[8] <=> (int) $data1[8];
}
};
foreach ($json->data as $data) {
$bikeSpaces->insert($data);
}
$bikeSpaces = new class($bikeSpaces) extends FilterIterator
{
public function accept()
{
return $this->current()[10] == 'MARKET';
}
};
foreach ($bikeSpaces as $b) {
echo $b[8] . ' Spaces: ' . $b[12] . '<br>';
}
\ No newline at end of file
<?php
class Language {
private $message;
public function __construct($lang)
{
switch($lang) {
case 'PHP':
$this->message = 'PHP 7 rocks.';
break;
case 'JavaScript':
$this->message = 'Front-end heaven or hell?';
break;
default:
$this->message = 'Tell me more.';
}
}
}
$getMessage = function($level) {
return $this->message . ' Popularity level: ' . $level . '.';
};
$lang = new Language('Pascal');
$m = $getMessage->bindTo($lang, 'Language');
echo $m(2);
<?php
function generator1() {
yield 1;
$g2 = yield from generator2();
yield 7;
return $g2;
}
function generator2() {
yield 2;
yield from [3, 4, 5];
yield 6;
return 'This came from generator2';
}
$gen = generator1();
foreach ($gen as $yielded) {
echo $yielded . '<br>';
}
echo $gen->getReturn();
\ No newline at end of file
<?php
function getCube(array $numbers) {
foreach ($numbers as &$num) {