📜 ⬆️ ⬇️

PHP7 Guide


php7-tutorial.com


The purpose of this site is to help you discover innovations in PHP 7. This guide is a set of simple exercises in which you will be asked to solve something, or to correct a mistake. Each exercise conforms to the RFC standard (a set of technical specifications and standards) and is accompanied by a brief explanation.

From translator


Hello everyone, Maxim Ivanov with you, and today we will talk about the innovations of PHP 7, which Guillaume Dievart will tell us in more detail in his guide, made in the form of exercises. But before starting, I want to point out one moment. I will not provide a complete guide to this programming language in this review, just leave here a link to the latest and most accurate information. Josh Lockhart (author of the PHP Guide: The Right Way, developer of the Slim Framework) wrote this book to help newbies, he said: reliable information on the PHP language, so my guide is designed to solve this problem. " What exactly? You know that a huge amount of PHP content is scattered around the Internet, but much has become outdated or does not lead to writing high-quality code. This book contains basic current information with links to trusted resources. If anyone is interested, this is in JavaScript . Now back to the exercises and get started.


Content


  1. Exercise 1. Change the value of the variable $ phpVersion
  2. Exercise 2. Replace the invalid tag
  3. Exercise 3. Replace the deprecated feature.
  4. Exercise 4. Use only __construct ()
  5. Exercise 5. Remove unnecessary default constructs in switch
  6. Exercise 6. Use the spaceship operator to sort an array
  7. Exercise 7. Use the join operator
  8. Exercise 8. It is necessary to modify the condition after the join operator
  9. Exercise 9. Change the value of $ b for the join operator to work correctly.
  10. Exercise 10. Group namespaces with the same prefix.
  11. Exercise 11. Rename method using new set of allowed keywords.
  12. Exercise 12. Use safer functions to generate random numbers.
  13. Exercise 13. Use the new preg_replace_callback_array function.
  14. Exercise 14. Use an anonymous class.
  15. Exercise 15. Specify the type in the function arguments
  16. Exercise 16. Modify the right operand of the condition to catch the value of the expected type
  17. Exercise 17. Use strict mode to catch errors when the function receives the wrong type.
  18. Exercise 18. Use strict mode for built-in functions.
  19. Exercise 19. The strict_types directive should be the first line
  20. Exercise 20. Specify the return type of the function.
  21. Exercise 21. Correct the return type of the function to catch the value of the expected type.
  22. Exercise 22. The definition of an inherited class should return the same type of its parent.
  23. Exercise 23. Use new unicode sequence to describe characters.
  24. Exercise 24. It is allowed to pass objects to the unserialize () function.
  25. Exercise 25. Turn on the generator another generator
  26. Exercise 26. Use the function closure
  27. Exercise 27. Call the variable $ c from $ a
  28. Exercise 28. Use the Error class to handle errors.
  29. Exercise 29. Use the TypeError class to handle errors.
  30. Exercise 30. Use the Throwable class to handle errors.
  31. Exercise 31. Use the DivisionByZeroError class to handle errors
  32. Exercise 32. Do not use hexadecimal numbers in strings.
  33. Exercise 33. Get the final value of the generator number 1
  34. Exercise 34. Get the final value of the generator number 2
  35. Exercise 35. Fix the prototype (interface) function
  36. Exercise 36. Create a group of constants

')

Sandbox


If you want to test some examples, use the online interpreter .

Exercise 1 . Change the value of the $ phpVersion variable to proceed to the next exercise.


<?php $phpVersion = 6; echo PHP_MAJOR_VERSION === $phpVersion ? "Next step !" : "No !"; 

 //  No ! 

Decision
 <?php $phpVersion = 7; echo PHP_MAJOR_VERSION === $phpVersion ? "Next step !" : "No !"; //  Next step ! 



To read:

1. The main reasons why you missed the sixth version and moved to the seventh
2. Operator output line on the screen
3. Ternary (conditional) operator
4. What is a major and minor version?

Exercise 2 . Replace invalid tag


 <?% echo "Next step !"; 

 //  syntax error, unexpected '%', expecting end of file on line 1 

Decision
 <?php echo "Next step !"; //  Next step ! 



To read:

1. Which alternative PHP tags were removed and which were left?

Exercise 3 . The ereg_replace function is obsolete; replace it with preg_replace


 <?php if (ereg_replace("PHP([3-6])", "PHP7", "PHP6")) { echo "Next step !"; } 

 //  Uncaught Error: Call to undefined function ereg_replace() in /tmp/__hoa_6b3Hmf:3 Stack trace: #0 /tmp/__hoa_f8PIGz(52): require() #1 {main} thrown on line 3 

Decision
 <?php if (preg_replace("/PHP([3-6])/", "PHP7", "PHP6")) { echo "Next step !"; } //  Next step ! 



To read:

1. Outdated Extensions
2. Regular expressions in PHP
3. Search and replace by regular expression
4. Templates
5. Performance

Exercise 4 . PHP4 constructors are deprecated, use __construct


 <?php class Foo { public function foo() { } } echo "Next step !"; 

 //  Methods with the same name as their class will not be constructors in a future version of PHP; Foo has a deprecated constructor on line 3 

Decision
 <?php class Foo { public function __construct() { } } echo "Next step !"; //  Next step ! 



To read:

1. Outdated Designer
2. Constructor (object-oriented programming)
3. What are classes for?
4. Why do I need OOP?
5. Object Oriented Programming
6. Basics of OOP in PHP
7. Stop writing classes.
8. Pros and cons of object-oriented programming

Exercise 5 . Multiple default constructs in the switch statement are now disabled; delete the first


 <?php switch ('') { default: echo "Doesn't pass here ..."; break; default: echo "Next step !"; } 

 //  Switch statements may only contain one default clause on line 7 

Decision
 <?php switch ('') { default: echo "Next step !"; } //  Next step ! 



To read:

1. Why does a syntax error occur in defining several cases by default in a switch statement?
2. Switch statement

Exercise 6 . Use spaceship operator (<=>) to sort an array


 <?php $users = ['Pierre', 'Paul', 'Next step !']; usort($users, function ($a, $b) { }); echo current($users); 

 //  Pierre 

Decision
 <?php $users = ['Pierre', 'Paul', 'Next step !']; usort($users, function ($a, $b) { return $a <=> $b; }); echo current($users); //  Next step ! 



To read:

1. New operator
2. What is this shaceship <=>?
3. usort - sorts an array by value, using a custom function to compare elements
4. Internal pointer

Exercise 7 . Use the union operator with a NULL value (??)


 <?php echo $_GET['query'] ? $_GET['query'] : "Next step !"; 

 //  Undefined index: query on line 3 

Decision
 <?php echo $_GET['query'] ?? "Next step !"; //  Next step ! 



To read:

1. New operator
2. Null coalescing operator
3. Simple PHP isset test
4. isset () vs empty () vs is_null ()

Exercise 8 . A union statement with a value of NULL (??) does not check the value in certain cases, change the right operand in the condition


 <?php $_GET['title'] = false; //    ,    $query = $_GET['title'] ?? '*'; // true //     if($query === '*') { echo "Next step !"; } 

 //  

Decision
 <?php $_GET['title'] = false; $query = $_GET['title'] ?? '*'; if($query === false) { echo "Next step !"; } //  Next step ! 



To read:

1. A special case

Exercise 9 . A union statement with a NULL value (??) does not check the value in certain cases; change the value of $ b


 <?php $b = false; echo $a ?? $b ?? "Next step !"; 

 //  

Decision
 <?php $b = null; echo $a ?? $b ?? "Next step !"; //  Next step ! 



To read:

1. An example of the operator

Exercise 10 . You can group namespaces with the same prefix. Group them in an example.


 <?php use Foo\Bar\Email; use Foo\Bar\Phone; use Foo\Bar\Address\Code; use Foo\Bar\Address\Number; echo "Next step !"; 

 //  Next step ! 

Decision
 <?php use Foo\Bar\{ Email, Phone, Address\Code, Address\Number }; echo "Next step !"; //  Next step ! 



To read:

1. Namespace (programming)
2. Overview of Namespaces
3. Namespaces in PHP, explanation
4. Namespaces in PHP
5. A brief introduction to PHP Namespaces

Exercise 11 . Some keywords can now be used in method names (list, foreach, new, ..)


 <?php class Foo { //   public function getList() { return "Next step !"; } } echo (new Foo)->list(); 

 //  Uncaught Error: Call to undefined method Foo::list() in /tmp/__hoa_FmqgZ0:12 Stack trace: #0 /tmp/__hoa_LbZpe8(52): require() #1 {main} thrown on line 12 

Decision
 <?php class Foo { public function list() { return "Next step !"; } } echo (new Foo)->list(); //  Next step ! 



To read:

1. Keywords

Exercise 12 . Use safer functions to generate random numbers.


 <?php $randomInt = mt_rand(0, 42); echo $randomInt; 

 //  5 

Decision
 <?php $randomInt = random_int(0, 42); echo $randomInt; //  1 



To read:

1. A cryptographically safe function for obtaining pseudo-random integers.
2. What is the disadvantage of mt_rand?
3. Difference between mt_rand () and rand ()

Exercise 13 . Use the new preg_replace_callback_array function


 <?php // Use preg_replace_callback_array instead of preg_replace_callback echo preg_replace_callback( array( "/PHP6/", "/PHP7/" ), function($matches) { if(strpos($matches[0], 'PHP6') === 0) { return 'Ko !'; } else { return "Next step !"; } }, 'PHP7' ); 

 //  Next step ! 

Decision
 <?php // preg_replace_callback_array  preg_replace_callback echo preg_replace_callback_array( array( "/PHP6/" => function() { return "Ko !"; }, "/PHP7/" => function() { return "Next step !"; }, ), 'PHP7' ); //  Next step ! 



To read:

1. Regular Expression Search and Replace Using Callback Function
2. Work with preg_replace_callback_array

Exercise 14 . Now you can create anonymous classes. Use an anonymous class instead of MyMessage


 <?php class Logger { public static function write(Message $message) { echo $message->getText(); } } interface Message { public function getText(); } class MyMessage implements Message { public function getText() { return "Next step !"; } } Logger::write(new MyMessage()); 

 //  Next step ! 

Decision
 <?php class Logger { public static function write(Message $message) { echo $message->getText(); } } interface Message { public function getText(); } $message = (new class() implements Message { public function getText() { return "Next step !"; } }); Logger::write($message); //  Next step ! 



To read:

1. Interfaces of objects
2. What is the essence of interfaces in PHP?
3. Programming template "Flowing Interface" in PHP. A fresh look
4. Abstract classes
5. Abstract classes and interfaces in PHP
6. Differences of the abstract class from the interface

Exercise 15 . Add int type to add function arguments


 <?php function add($a, $b) { return $a + $b; } if(add(5.5, 5) === 10) { echo "Next step !"; } 

 //  

Decision
 <?php function add(int $a, int $b) { return $a + $b; } if(add(5.5, 5) === 10) { echo "Next step !"; } //  Next step ! 



To read:

1. Type of data
2. Introduction to PHP Data Types
3. Today, the use of scalar and mixed data types in PHP 7 does not improve performance.

Exercise 16 . By default, PHP casts the value of the expected type. Modify the right operand of the condition


 <?php function add(int $a, int $b) { return $a + $b; } //    if(add(5.5, 5.5) === 11) { echo "Next step !"; } 

 //  

Decision
 <?php function add(int $a, int $b) { return $a + $b; } if(add(5.5, 5.5) === 10) { echo "Next step !"; } //  Next step ! 



To read:

1. Initialization of scalar types in PHP 7

Exercise 17 . Use strict mode if you want to intercept errors, in the case where the function gets the wrong type that it expects. Fix on float.


 <?php declare(strict_types = 1); function add(int $a, int $b) { return (int)($a + $b); } if(add(5.5, 5.5) === 11) { echo "Next step !"; } 

 //  Uncaught TypeError: Argument 1 passed to add() must be of the type integer, float given, called in /tmp/__hoa_FKwVHc on line 10 and defined in /tmp/__hoa_FKwVHc:5 Stack trace: #0 /tmp/__hoa_FKwVHc(10): add(5.5, 5.5) #1 /tmp/__hoa_rejBtd(52): require('/tmp/__hoa_FKwV...') #2 {main} thrown on line 5 

Decision
 <?php declare(strict_types = 1); function add(float $a, float $b) { return (int)($a + $b); } if(add(5.5, 5.5) === 11) { echo "Next step !"; } //  Next step ! 



To read:

1. Manipulations with data types
2. Setting directives
3. Type control
4. Built-in directives

Exercise 18 . Use strict mode for built-in functions.


 <?php declare(strict_types = 1); strlen(42); echo "Next step !"; 

 //  Uncaught TypeError: strlen() expects parameter 1 to be string, integer given in /tmp/__hoa_0HYwi9:3 Stack trace: #0 /tmp/__hoa_CjotyX(52): require() #1 {main} thrown on line 3 

Decision
 <?php declare(strict_types = 1); strlen('42'); echo "Next step !"; //  Next step ! 



To read:

1. Reference Standard Functions
2. Built-in functions in PHP
3. Built-in PHP extensions
4. Standard PHP Library (SPL)

Exercise 19 . The strict_types directive should be the first line


 <?php echo "Next step !"; declare(strict_types = 1); 

 //  strict_types declaration must be the very first statement in the script on line 5 

Decision
 <?php declare(strict_types = 1); echo "Next step !"; //  Next step ! 



To read:

1. declare is used to set execution directives for a code block.

Exercise 20 . Now you can specify the type of return value for the function or method. Specify the return type of the function.


 <?php function reverse(string $string): type { return strrev($string); } echo reverse("! pets txeN"); 

 //  Uncaught TypeError: Return value of reverse() must be an instance of type, string returned in /tmp/__hoa_ZcQkYd:5 Stack trace: #0 /tmp/__hoa_ZcQkYd(8): reverse('! pets txeN') #1 /tmp/__hoa_7JLJ4t(52): require('/tmp/__hoa_ZcQk...') #2 {main} thrown on line 5 

Decision
 <?php function reverse(string $string): string { return strrev($string); } echo reverse("! pets txeN"); echo "Next step !"; //  Next step ! 



To read:

1. Return Values
2. What is the difference between return and non return value in PHP?
3. Do we win in performance if we suggest functions to the expected type in PHP?
4. Are there any rules for the return value of a custom Boolean function?

Exercise 21 . By default, PHP will throw the expected type. Correct the return type of the function.


 <?php // : function foo(): int { return 5.5; } echo foo(); // 5 function add(float $a, float $b): int { return $a + $b; } //    if(add(5.3, 5.3) === 10.6) { echo 'Next step !'; } 

 //  

Decision
 <?php function add(float $a, float $b): int { return $a + $b; } // Modify the right operand. if(add(5.3, 5.3) === 10) { echo 'Next step !'; } //  Next step ! 



To read:

1. Return by reference
2. Reference Guide

Exercise 22 . The definition of an inherited class must return the same type of its parent.


 <?php class Child {} class ChildB extends Child {} abstract class A { abstract public function foo(): Child; } class B extends A { public function foo(): ChildB { return new ChildB; } } echo "Next step !"; 

 //  Declaration of B::foo(): ChildB must be compatible with A::foo(): Child on line 17 

Decision
 <?php class Child {} class ChildB extends Child {} abstract class A { abstract public function foo(): Child; } class B extends A { public function foo(): Child { return new ChildB; } } echo "Next step !"; //  Next step ! 



To read:

1. A bit about inheritance and redefinition of methods than about polymorphism
2. What polymorphism really is. In PHP, it also exists
2. When the subtype overlaps the parent method, the type of the returned child method must exactly match the parent
4. Excellent educational course on learning OOP in PHP

Exercise 23 . Now you can use a unicode sequence to describe characters.


 <?php //    if("\?{26C4}" === '') { echo "Next step !"; } 

 //  

Decision
 <?php // Modify the left operand. if("\u{26C4}" === '') { echo "Next step !"; } //  Next step ! 



To read:

1. Unicode
2. Unicode characters in a PHP string
3. Unicode control (escape-) sequence support

Exercise 24 . A new option has been added to the standard unserialize () function, now it is allowed to specify classes. Specify the class in the unserialize () function


 <?php class MyClass { } $myClassSerialized = serialize(new MyClass()); $myClass = unserialize( $myClassSerialized, ["allowed_classes" => ['']] ); if($myClass instanceOf MyCLass) { echo "Next step !"; } 

 //  

Decision
 <?php class MyClass { } $myClassSerialized = serialize(new MyClass()); $myClass = unserialize( $myClassSerialized, ["allowed_classes" => ['MyClass']] ); if($myClass instanceOf MyCLass) { echo "Next step !"; } //  Next step ! 



To read:

1. unserialize
2. How to use serialize () and unserialize () in PHP?
3. Operator type check

Exercise 25 . Delegation of generators allows returning another iterable structure - be it an object, an array, an iterator, or another generator. Turn on the generator another generator


 <?php function generator() { yield 1; // 'yield'  «           yield 2; //      } function subGenerator() { yield 3; yield 4; yield "Next step !"; } $generator = generator(); foreach($generator as $value) { echo $value.PHP_EOL; } 

 //  1 2 

Decision
 <?php function generator() { yield 1; yield 2; yield from subGenerator(); } function subGenerator() { yield 3; yield 4; yield "Next step !"; } $generator = generator(); foreach($generator as $value) { echo $value.PHP_EOL; } //  1 2 3 4 Next step ! 



To read:

1. Support for generators and coroutines: the essence of the generator is that it is a function that returns not just one value, but a sequence of values
2. Generators in action
3. Save memory using generators
4. Delegation of generators
5. About resource leaks in PHP generators

Exercise 26 . You can use short circuits in functions. New interpreter running from left to right


 <?php function foo() { return function() { echo "Next step !"; }; } //    foo    

 //  

Decision
 <?php function foo() { return function() { echo "Next step !"; }; } // : $foo = foo(); $foo(); foo()(); //  Next step ! 



To read:

1. Anonymous function (lambda function)
2. Anonymous functions (closures) in PHP: not to be confused with closures in JavaScript
3. Applying closures in PHP

Exercise 27 . Correct the syntax to call the $ c variable from $ a


 <?php $a = ['b' => 'c']; $c = 'Next step !'; //    Next step !  PHP5 echo $$a['b']; 

 //  Undefined variable: Array on line 7 

Decision
 <?php $a = ['b' => 'c']; $c = 'Next step !'; echo ${$a['b']}; //  Next step ! 



To read:

1. Universal syntax

Exercise 28 . Now, to catch an exception, you must use the Error class.


 <?php try { //    undefinedFunction(); } catch(Exception $e) { echo "Next step !"; } 

 //  Uncaught Error: Call to undefined function undefinedFunction() in /tmp/__hoa_PaBzqc:4 Stack trace: #0 /tmp/__hoa_SQZOZG(52): require() #1 {main} thrown on line 4 

Decision
 <?php try { undefinedFunction(); } catch(Error $e) { echo "Next step !"; } //  Next step ! 



To read:

1. Exception handling
2. Why do we need exception handling?
3. Exceptions in PHP
4. Throwable exception and errors in PHP 7

Exercise 29 . You can also use the TypeError class to handle exceptions.


 <?php declare(strict_types = 1); function add(int $a, int $b): int { return $a + $b; } // Catch the TypeError try { echo add('1', '1'); } catch(Exception $e) { echo "Next step !"; } 

 //  Uncaught TypeError: Argument 1 passed to add() must be of the type integer, string given, called in /tmp/__hoa_FvS6wW on line 12 and defined in /tmp/__hoa_FvS6wW:5 Stack trace: #0 /tmp/__hoa_FvS6wW(12): add('1', '1') #1 /tmp/__hoa_kfhSdT(52): require('/tmp/__hoa_FvS6...') #2 {main} thrown on line 5 

Decision
 <?php declare(strict_types = 1); function add(int $a, int $b): int { return $a + $b; } // Catch the TypeError try { echo add('1', '1'); } catch(TypeError $e) { echo "Next step !"; } //  Next step ! 



To read:

1. Types of exceptions in PHP

Exercise 30 . Use Throwable to catch exceptions and errors (common Errors, Exceptions interface)


 <?php //    CallErrorAndException try { if(random_int(0, 1) === 1) { throw new Exception(''); } undefined(); } catch(CallErrorAndException $e) { echo "Next step !"; } 

 //  Undefined offset: -1 on line 55 

Decision
 <?php try { if(random_int(0, 1) === 1) { throw new Exception(''); } undefined(); } catch(Throwable $e) { echo "Next step !"; } //  Next step ! 



To read:

1. Exception! = Error
2. Using Throwable
3. Example of division by zero

Exercise 31 . Use DivisionByZeroError when dividing by zero


 <?php try { 10 % 0; } catch(CatchError $e) { echo "Next step !"; } 

 //  Uncaught DivisionByZeroError: Modulo by zero in /tmp/__hoa_46SBwZ:5 Stack trace: #0 /tmp/__hoa_UQ8f3n(52): require() #1 {main} thrown on line 5 

Decision
 <?php try { 10 % 0; } catch(DivisionByZeroError $e) { echo "Next step !"; } //  Next step ! 



To read:

1. DivisionByZeroError

Exercise 32 . Do not use hexadecimal numbers in strings.


 <?php // var_dump(12 == "0xC"); // true  PHP 5 // var_dump(12 == "0xC"); // false  PHP 7 //    if('0x2A' == 42) { echo "Next step !"; } 

 //  

Decision
 <?php if(0x2A == 42) { echo "Next step !"; } //  Next step ! 



To read:

1. Type casting in PHP == stool with two legs?
2. Type cast
3. Removed support for hexadecimal numbers in strings

Exercise 33 . Explicitly returning the final value of the generator allows you to process the value directly in the code calling the generator


 <?php //  Generator::getReturn()     function generator() { yield 21; yield 21; return true; } $generator = generator(); foreach($generator as $number) { } if($generator->callReturn() === true) { echo "Next step !"; } 

 //  Uncaught Error: Call to undefined method Generator::callReturn() in /tmp/__hoa_eOhq2B:14 Stack trace: #0 /tmp/__hoa_sa29ov(52): require() #1 {main} thrown on line 14 

Decision
 <?php function generator() { yield 21; yield 21; return true; } $generator = generator(); foreach($generator as $number) { } if($generator->getReturn() === true) { echo "Next step !"; } //  Next step ! 



To read:

1. Return the final value

Exercise 34 . Unable to get final value if inner pointer does not point to it.


 <?php function generator() { yield 21; yield 21; return "Next step !"; } $generator = generator(); $generator->next(); echo $generator->getReturn(); 

 //  // caught: Cannot get return value of a generator that hasn't returned 

Decision
 <?php function generator() { yield 21; yield 21; return "Next step !"; } $generator = generator(); $generator->next(); $generator->next(); echo $generator->getReturn(); //  Next step ! 



To read:

1. How to say in Russian the word yield ???

Exercise 35 . You cannot use the same argument names in the function prototype.


 <?php function foo($a, $a) { return $a; } echo foo("Next ", "step !"); //  PHP5: step ! 

 //  Redefinition of parameter $a on line 4 

Decision
 <?php function foo($a, $b) { return $a . $b; } echo foo("Next ", "step !"); //  Next step ! 



To read:

1. Function Arguments

Exercise 36 . Now you can create an array (group) of constants


 <?php $conf = [ 'user' => 'root', 'password' => 'my_password', 'step' => 'Next step !' ]; //  CONFIGURATION   echo CONFIGURATION['step']; 

 //  /* * <br /> * <b>Warning</b>: Illegal string offset 'step' in <b>/tmp/__hoa_dBF385</b> on line <b>11</b><br /> */ 

Decision
 <?php $conf = [ 'user' => 'root', 'password' => 'my_password', 'step' => 'Next step !' ]; define('CONFIGURATION', $conf); echo CONFIGURATION['step']; //  Next step ! 



To read:

1. Constants
2. "Magic" constants
3. define () vs const

Source: https://habr.com/ru/post/302942/


All Articles