PHP Language Revision of Fundamentals Martin Kruli by
PHP Language Revision of Fundamentals Martin Kruliš by Martin Kruliš (v 2. 0) 28. 2. 2019 1
Revision of PHP Fundamentals � Basic ◦ ◦ ◦ Syntax C-like syntax with relicts from Perl Specialties and differences foreach – iteration over structures String concatenation $str 1. $str 2 Equality == vs identity === comparison Spaceship operator $a <=> $b �Returns -1, 0, or 1 if $a is lesser, equal, or greater $b ◦ Null coalescing operator $a ? ? $b �Returns first operand if exists and not null, otherwise returns second operand by Martin Kruliš (v 2. 0) 28. 2. 2019 2
Revision of PHP Fundamentals � Dynamic ◦ Values Nature of PHP �Exist in a managed memory space �Created as literals, results of expressions, or by internal constructions and functions �Explicit data types, but weak typing �boolean, integer, float, string, array, object, resource, null ◦ Memory Management �Uses copy-on-write and reference counting �Values are not always copied on assignment �Once a value has zero references, it is garbage collected by Martin Kruliš (v 2. 0) 28. 2. 2019 3
Revision of PHP Fundamentals � Dynamic Nature of PHP ◦ Variables �Mnemonic references to values �No declarations, created on the first assignment �In the global or local scope �Globals can be mapped into local context (global keyword) �No explicit type (type is determined by current value) �Type can be changed with a new assignment �Existence can be tested (isset) and terminated (unset) ◦ Arrays �An array item behaves in many ways like a variable by Martin Kruliš (v 2. 0) 28. 2. 2019 4
Revision of PHP Fundamentals � Strings and Text Processing ◦ Preprocessed string literals "We have $foo. Count foos. n" ◦ PHP have a huge arsenal of string functions �strlen(), substr(), trim(), explode(), join(), … ◦ Libs for charset manipulation �Multibyte string lib, Iconv lib, Recode ◦ Functions for typical cases �urlencode(), htmlspecialchars(), … ◦ Regular expressions �preg_match(), preg_replace(), preg_split() by Martin Kruliš (v 2. 0) 28. 2. 2019 5
Revision of PHP Fundamentals � Arrays ◦ Array in PHP is an ordered map of key-value pairs �Can be used as array, list, hash table, dictionary, stack/queue, multi-dimensional array, or tree ◦ Defining arrays – array language construct $a 1 = array(1, 2, 3); $a 1 = [1, 2, 3]; $a 2 = array('foo' => 42, 'bar' => 54); ◦ Accessing elements Prints ’ 44’ echo $a 1[1] + $a 2['foo']; $a 2['spam'] = 19; $a 1[] = 4; The following key is assigned unset($a 1[2]); ◦ Each element may have different type $a 1 ~ [0=>1, 1=>2, 3=>4] by Martin Kruliš (v 2. 0) 28. 2. 2019 6
Variables � Indirect Access to Values ◦ Name of one variable is stored in another variable $a = 'b'; $$a = 42; // the same as $b = 42; $a = 'b'; $b = 'c'; $c = 'd'; $$$$a = 'hello'; // the same as $d = 'hello'; ◦ The {, } can be used to avoid ambiguous situations ◦ Can be used with members, functions, classes, … $obj = new $class. Name(); $obj->$var. Name = 42; by Martin Kruliš (v 2. 0) 28. 2. 2019 7
References � References ◦ Similar to Unix hard-links in FS ◦ Multiple variables attached to the same data �Reference is taken by the & operator ◦ Independent on object references �A reference to an object can be created $a = 1; $b = &$a; $b++; echo $a; // prints 2 $a int (2) (1) $b by Martin Kruliš (v 2. 0) 28. 2. 2019 8
References in Functions � Arguments as References ◦ Similar usage as var keyword in Pascal function inc(&$x) { $x++; } � Returning References function &find. It($what) { global $my. Array; return &$my. Array[$what]; } Useful applications are rather limited by Martin Kruliš (v 2. 0) 28. 2. 2019 9
References � References vs. Pointers function foo(&$var) { $var = &$GLOBALS['bar']; } � The unset() Function � The global Declaration $x = 42; foo($x); How is $x affected? ◦ Does not remove data, only the variable ◦ Data are removed when not referenced global $a; $a = &$GLOBALS['a']; by Martin Kruliš (v 2. 0) 28. 2. 2019 10
Revising PHP Functions � Declaration ◦ Keyword function followed by the identifier function foo([args, …]) { … body … } ◦ Function body �Pretty much anything (even a function/class decl. ) �Nested functions/classes are declared once the function is called for the first time �Functions are 2 nd level citizens and identifier space is flat ◦ Results �Optional argument of the return construct �Only one value, but it can be an array or an object by Martin Kruliš (v 2. 0) 28. 2. 2019 11
Function Arguments � Argument Declarations ◦ Implicit values may be provided function foo($x, $y = 1, $z = 2) { … } �Arguments with implicit values are aligned to the right �Note that PHP functions does not support overloading � Variable Number of Arguments ◦ func_num_args(), func_get_args() ◦ function foo($a, $b, . . . $rest) �$rest gets remaining arguments as an array ◦ Splat operator (…) works also for argument unpacking $args = [1, 2]; foo(. . . $args); // foo(1, 2); by Martin Kruliš (v 2. 0) 28. 2. 2019 12
Static Variables � Static Variables in Function ◦ Initialized on the first call ◦ Keep their values to subsequent calls Initial value must be a literal or an expression of literals (resolvable at compile time) function foo() { static $calls = 0; ++$calls; echo "foo() called $calls times. . . "; } foo(); // foo() called 1 times. . . foo(); // foo() called 2 times. . . by Martin Kruliš (v 2. 0) 28. 2. 2019 13
Variable Functions � Indirect Calling ◦ Calling a function by its name stored in a variable function foo($x, $y) { … } $func. Name = 'foo'; $func. Name(42, 54); // the same as foo(42, 54); � Similar Constructs ◦ Using specialized invocation functions �call_user_func('foo', 42, 54); �call_user_func_array('foo', array(42, 54)); by Martin Kruliš (v 2. 0) 28. 2. 2019 14
Anonymous Functions � Anonymous Functions ◦ Better way how to implement nameless functions $fnc = function($args) { …body… }; ◦ The anonymous function is an instance of Closure �It can be passed on like an object ◦ The visible variables must be explicitly stated $fnc = function(…) use ($var, &$refvar) { … }; �These variables are captured in the closure �Variables passed by reference can be modified by Martin Kruliš (v 2. 0) 28. 2. 2019 15
Type Hinting � Controlling Types of Function Arguments ◦ Arguments may be prefixed with data type �Regular type (string, array, …), class/interface name, callable, iterable, … ◦ Type prefixed with ? means null is also acceptable ◦ Return type may be also specified ◦ Automatic type coercing applied if possible �Type. Error exception thrown on error �Strict mode disables coercing declare(strict_types=1); function foo(My. Class $obj, ? array $params): int by Martin Kruliš (v 2. 0) 28. 2. 2019 16
Class Declarations member visibility class Foo { public $var = 0; public function bar() { echo $this->var; } // a member variable // a method } $instance = new Foo(); $instance->var = 42; $instance->bar(); $instance = null; // create new instance by Martin Kruliš (v 2. 0) 28. 2. 2019 17
Objects & References � Objects Are Reference Types ◦ Like in Java or C# class Foo { public $bar = 0; public function __construct($b) { $this->bar = $b; } } $foo 1 = new Foo(10); objref#2 Foo(20) $foo 2 objref#1 $foo 2 = $foo 1; $foo 3 = &$foo 1; objref#3 $foo 1 objref#1 Foo(10) $foo 2 = new Foo(20); $foo 3 = new Foo(30); Foo(30) $foo 3 by Martin Kruliš (v 2. 0) 28. 2. 2019 18
Dynamic Nature of Classes � Member Variables are Dynamic class Point { public $x = 1; public $y = 2; } $p = new Point(); vs. $p = new std. Class(); $p->x = 1; $p->y = 2; Base class without any members (used also for implicit object constructions) ◦ Why declare members in classes? �Visibility control �Default values (initialization) �Better readability (documentation comments, …) �Reflection by Martin Kruliš (v 2. 0) 28. 2. 2019 19
Inheritance � Standard Inheritance Model ◦ Each class may have only one parent class �Multi-inheritance is achieved by interfaces and traits � Overriding Methods ◦ All methods act as if they are virtual ◦ parent: : method() – calling overridden version �Ancestor. Class: : method() – calling explicit version ◦ Methods tagged as final cannot be overridden class My. Foo extends Foo { public function Bar() { parent: : Bar(); } } by Martin Kruliš (v 2. 0) 28. 2. 2019 20
Static Members � Static (Class) Members ◦ Declared by static keyword before the member ◦ Accessed by : : operator (like constants) �E. g. , My. Class: : $stat. Var or My. Class: : my. Func() ◦ One instance, no matter how many objects class has �I. e. , static methods does not have $this ◦ The same types of visibility as regular members ◦ Small differences in inheritance new variable class A { public static $x; } class B extends A { public static $x; } class C extends A {} … C: : $x = 42; same as A: : $x by Martin Kruliš (v 2. 0) 28. 2. 2019 21
Late Static Binding � Late Binding for Static Calls ◦ When static: : is used instead of self: : class A { public static function who() { echo __CLASS__; } public static function test() { self: : who(); static: : who(); } } class B extends A { public static function who() { echo __CLASS__; } } B: : test(); Prints ‘A’ Prints ‘B’ by Martin Kruliš (v 2. 0) 28. 2. 2019 22
Abstract Entities � Abstract Classes and Methods ◦ Prefixed with keyword abstract ◦ Abstract class cannot be instantiated ◦ Abstract method has no body �It is expected to be implemented in derived class abstract class Abstract. Class { abstract function foo(); } class Concrete. Class extends Abstract. Class { function foo() { … foo body … } } $obj = new Concrete. Class(); by Martin Kruliš (v 2. 0) 28. 2. 2019 23
Interfaces � Interfaces ◦ List of public methods a class must implement ◦ Interfaces may be extended like classes �Using the extends operator interface IFoo { public function bar($goo); } class Foo implements IFoo { public function bar($goo) {. . . Unlike in case of inheritance, } a class may implement } multiple interfaces by Martin Kruliš (v 2. 0) 28. 2. 2019 24
Traits � Traits ◦ Class-like mechanism for code reuse �Horizontal composition of behavior (similar to Mixins) ◦ Trait �Special class that cannot be instantiated �May contain both member variables and methods �It can be added to regular classes trait Omni. Saluter { public function hello. World() { echo 'Hello World'; } } class my. Class { use Omni. Saluter; . . . by Martin Kruliš (v 2. 0) 28. 2. 2019 25
Object Iterators � Iterating Member Variables ◦ By foreach construct (like arrays) �Keys are strings with the name of the member �Only visible (accessible) members are iterated class My. Class { public $var 1 = 1; public $var 2 = 2; private $var 3 = 3; } $obj = new My. Class(); foreach ($obj as $key => $value) {. . . } ◦ Custom iteration can be implemented �Interface Iterator and Iterator. Aggregate by Martin Kruliš (v 2. 0) 28. 2. 2019 26
Object Iterators Example class Array. Wrapper implements Iterator { private $items = [ 1, 2, 3 ]; public function rewind() { // initialize for new iteration reset($this->items); } public function current() { // value at actual position return current($this->items); } public function key() { // key at actual position return key($this->items); } public function next() { // advance position by one step return next($this->items); } public function valid() { // is current position valid return ($this->current() !== false); } } by Martin Kruliš (v 2. 0) 28. 2. 2019 27
Generators � Detached Custom Iterators ◦ The foreach construct is powerful �But it iterates over structures (arrays and objects) ◦ Custom iterator can be built (Iterator interface) �Both memory demanding and tedious ◦ Generator is a function that yields values �It can be used in foreach construct Returns next value function range_gen($from, $to, $step) { for ($i = $from; $i < $to; $i += $step) yield $i; } Local context is preserved foreach (range_gen(1, 10, 2) as $value). . . by Martin Kruliš (v 2. 0) 28. 2. 2019 28
Object Cloning � Copying Reference vs. Copying Object ◦ Assignment copies reference, not the object ◦ Object copy must be invoked explicitly, by cloning $foo = new Foo(); $foo 2 = $foo; $foo 3 = clone $foo; $foo Foo object #1 $foo 2 $foo 3 Foo object #2 by Martin Kruliš (v 2. 0) 28. 2. 2019 29
Object Cloning � Shallow vs. Full Copy ◦ Cloning process creates shallow copy by default �Assignment operator is used on every member ◦ Post-cloning operations may be implemented in method __clone(), which is invoked on the copy public function __clone() { $this->inner. Obj = clone $this->inner. Obj; } $this is newly copied object, which has all members already assigned by Martin Kruliš (v 2. 0) 28. 2. 2019 30
Object Cloning Example class Inner. Foo { public $bar = 1; } class Foo { public $inner. Foo; public function __construct() { $this->inner. Foo = new Inner. Foo(); } Ensures deep copy public function __clone() { $this->inner. Foo = clone $this->inner. Foo; } } $foo = new Foo(); $foo 2 = clone $foo; by Martin Kruliš (v 2. 0) 28. 2. 2019 31
Magic Methods � Member ◦ ◦ ◦ Variables Accessors __get() – control read-access to members __set() – control write-access to members __isset() – isset() override for members __unset() – unset() override for members Overrides access to member variables, which are not declared or not visible �Declared variables are accessed directly �Only for regular members, not for static ◦ Handle with care �They may lead to less readable code or even errors by Martin Kruliš (v 2. 0) 28. 2. 2019 32
Magic Methods � Method Invocation Override ◦ __call() – intercepts calls to not visible methods ◦ __call. Static() – the same for static methods ◦ __invoke() – when object is called as function � Array ◦ ◦ ◦ Access Interface Allows using the object as an array ($obj[…]) boolean offset. Exists(mixed $offset) mixed offset. Get(mixed $offset) void offset. Set(mixed $offset, mixed $value) void offset. Unset(mixed $offset) by Martin Kruliš (v 2. 0) 28. 2. 2019 33
Magic Methods Example class Readonly { private $foo; . . . public function __construct($foo) { $this->foo = $foo; } public function __get($name) { return (isset($this->$name)) ? $this->$name; : null; } public function __isset($name) { return isset($this->$name); } public function __set($name, $value) { throw new Exception("Object is read only!"); } public function __unset($name) { throw new Exception("Object is read only!"); } } by Martin Kruliš (v 2. 0) 28. 2. 2019 34
Serialization � Object (De)Serialization ◦ Using magic methods �__sleep() – invoked when the object is being serialized (to a persistent storage) �__wakeup() – invoked when the object is being deserialized (from a persistent storage) �__to. String() – returns string representation of the object (e. g. , so it can be printed, logged, …) ◦ Using Serializable interface �string serialize(void) �void unserialize (string $serialized) by Martin Kruliš (v 2. 0) 28. 2. 2019 35
Comparing Objects � Reference Comparison Behavior ◦ $object 1 == $object 2 �True if both object are of the same class and all member variables are equal (==) ◦ $object 1 === $object 2 �True if both variables hold a reference to exactly the same object ◦ $object 1 < $object 2 �Works only on objects of the same class �Returns the result of comparison of the first non-equal property �Use with extra care (note that sort() uses comparisons) by Martin Kruliš (v 2. 0) 28. 2. 2019 36
Type Detection/Verification � Operator instanceof ◦ Verifies whether object is an instance of given class or derived class, or implements given interface if ($foo instanceof Foo. Class). . . � Functions ◦ ◦ Testing Types get_class() – returns class name as string get_parent_class() – name of the parent class is_a() – verifies that object is of given class is_subclass_of() – like is_a(), but checks also derived classes by Martin Kruliš (v 2. 0) 28. 2. 2019 37
Reflection � Reflection ◦ A mechanism implemented in (dynamic) languages to inspect types, objects, classes, etc. at runtime ◦ PHP holds a specific reflector class for each entity �Reflection. Type �Reflection. Function �Reflection. Class �Reflection. Object �Reflection. Property �Reflection. Parameter �… by Martin Kruliš (v 2. 0) 28. 2. 2019 38
Reflection � Reflection API in PHP ◦ An object of appropriate reflector is instantiated �E. g. , to list information about a class, an object of Reflection. Class is created (by the name of the class) ◦ Each reflector provides methods to access the data �Class/Object reflector allows listing properties, methods, constants, and inspect inheritance �Function/Method reflectors give information about arguments, modifiers, and creates dynamic closure �… ◦ API also provides access to doc comments /** … */ �Can be used for custom annotations by Martin Kruliš (v 2. 0) Example 28. 2. 2019 39
Namespaces � Namespaces ◦ Another way how to encapsulate space of identifiers �Affect classes, traits, interfaces, functions, constants �Similar to directories and files ◦ Declaration: namespace identifier; �First statement in the file �Identifier may be hierarchical (separator is backslash) ◦ Dereferencing �my. Class -> current. NSmy. Class �namespacemy. Class -> current. NSnamespacemy. Class �namespacemy. Class – absolute path, no modifications ◦ Aliasing – use identifier [as identifier]; by Martin Kruliš (v 2. 0) 28. 2. 2019 40
Anonymous Classes � Instant One-use Classes ◦ Similar to anonymous functions interface Logger { public function log(string $msg); }. . . $app->add. Logger(new class implements Logger { public function log(string $msg) { echo $msg; } }); by Martin Kruliš (v 2. 0) 28. 2. 2019 41
Discussion by Martin Kruliš (v 2. 0) 28. 2. 2019 42
- Slides: 42