PHP Language Details Martin Kruli by Martin Kruli
PHP – Language Details Martin Kruliš by Martin Kruliš (v 1. 0) 12. 2018 1
Revision of PHP Fundamentals � Dynamic Nature of PHP ◦ Dynamic weakly-typed language ◦ 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) ◦ Automatic casting (type juggling) by Martin Kruliš (v 1. 0) 12. 2018 2
Arrays � Arrays ◦ Array in PHP is an ordered map of key-value pairs �I. e. , maintaining order independent on keys �Key provides quick access to value ◦ Keys can be integers or strings ◦ Array holds internal pointer for iteration �reset($array) – rewinds the pointer �end($array) – sets the pointer to the last element �next($array), prev($array) – move the pointer �key($array), current($array) – actual key/value However, it is better to traverse the arrays using foreach by Martin Kruliš (v 1. 0) 12. 2018 3
Arrays � Sorting ◦ Slightly more complicated – many combinations sort(), asort(), ksort(), uksort(), … � Merging $res = array_merge($a, $b); � Tokenization ◦ explode($delim, $str) ◦ implode($glue, $array) � Destructive assignment list($a, $b, $c) = [1, 2, 3]; by Martin Kruliš (v 1. 0) 12. 2018 4
Arrays � Pitfalls All keys will be cast to 1 $a == [ 1 => 'd' ] $a = [ 1=>'a', '1'=>'b', 1. 5=>'c', true=>'d' ]; $a = [ 'a', 4 => 'b', 'c' ]; $a[42] = 'd'; $a[] = 'e'; Next index is last index + 1 (but at least 0) [ 1=>'a', 4=>'b', 5=>'c', 42=>'d', 43=>'e' ] (array)$scalar. Value == [ $scalar. Value ] (array)null == [] Scalar values are casted to single-item arrays, except for null by Martin Kruliš (v 1. 0) 12. 2018 5
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, … $fnc. Name = 'foo'; $fnc. Name(); // same as foo() by Martin Kruliš (v 1. 0) 12. 2018 6
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 1. 0) 12. 2018 7
References in Functions � Arguments as References ◦ Similar usage as var keyword in Pascal function inc(&$x) { $x++; } � Returning This is perhaps the most practical utilization of references References function &find. It($what) { global $my. Array; return &$my. Array[$what]; } Useful applications are rather limited by Martin Kruliš (v 1. 0) 12. 2018 8
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 1. 0) 12. 2018 9
References � Pitfalls ◦ There are too many… $array = [ 42, 54, 19 ]; foreach ($array as &$value) { ++$value; The reference lingers on… } unset($value); And here we assign to it again. . . foreach ($array as $value) { echo $value; } Now, the $array holds [ 43, 55 ] by Martin Kruliš (v 1. 0) 12. 2018 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 ◦ Type Hinting �Dynamic type checks for arguments and return value by Martin Kruliš (v 1. 0) 12. 2018 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 1. 0) 12. 2018 12
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 1. 0) 12. 2018 13
Anonymous Functions � Anonymous Functions $fnc = function($arg) { …body… }; $fnc(42); ◦ 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 ◦ Nameless/Lambda functions (obsolete) $mul = create_function('$x, $y', 'return $x*$y'); by Martin Kruliš (v 1. 0) 12. 2018 14
Anonymous Functions � Example $shopping_list = [ 'milk', 'spam', 'eggs', 'beer', '' ]; array_walk($shopping_list, function($item) { echo "$itemn"; Invoked once for every item }); function count. Valid. Items(array $list){ $count = 0; $callback = function($item) use (&$count) { if ($item) ++$count; Explicitly captured external }; variable (by reference) array_walk($list, $callback); return $count; } echo "Valid Items: ", count. Valid. Items($shopping_list); by Martin Kruliš (v 1. 0) 12. 2018 15
Object Oriented PHP � First attempt made in PHP 4 ◦ Poor design, failed � Current implementation in PHP 5 and 7 ◦ Design is inspired by languages like Java or C# ◦ Adaptations for interpreted loosely-typed language �E. g. , there are no “virtual” methods ◦ Powerful in combination with PHP-specific features �For instance with variables: $obj = new $class. Name(); $obj->$method. Name(); by Martin Kruliš (v 1. 0) 12. 2018 16
Syntax Basics 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 1. 0) 12. 2018 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 1. 0) 12. 2018 18
Member Variables � Member Visibility Type (is mandatory) ◦ public – accessible from anywhere ◦ protected – access. from within and derived classes ◦ private – only accessible from within the class � Implicit Member Declaration ◦ Created as public by default class Foo { private $bar; } $foo = new Foo(); $foo->bar = 1; $foo->barbar = 42; // Error! 'bar' is private // OK, new member is created by Martin Kruliš (v 1. 0) 12. 2018 19
Member Variables � 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 1. 0) 12. 2018 20
Member Functions (Methods) � Visibility Type ◦ The same meaning as for variables ◦ Optional, set as public if missing � Accessing the Object Instance ◦ Current object instance is available through $this ◦ It must be used to access member variables �To distinguish members from local variables � Otherwise the Same as Regular Functions ◦ No overloading, variadic, … by Martin Kruliš (v 1. 0) 12. 2018 21
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 1. 0) 12. 2018 22
Constructor � Special Method __construct() ◦ Used to initialize the object ◦ Called automatically (by the new operator) ◦ May have arguments �Same behavior as regular method (e. g. , no overloading) ◦ Does not have to be defined �Parent’s constructor or implicit constructor is used ◦ Parent’s constructor is not called implicitly ◦ Constructor should be public �Except for some special cases like Singleton or Factory Method design patterns by Martin Kruliš (v 1. 0) 12. 2018 23
Destructor � Special Method __destruct() ◦ Called when the object is garbage-collected �When ref. count reaches 0 or at the end of the script ◦ Does not have to be defined �Parent’s destructor or implicit destructor is used ◦ Destructor should not throw exceptions �Since they may not be handled properly ◦ Parent’s destructor is not called implicitly ◦ Destructor should be public �And there are no reasonable exceptions by Martin Kruliš (v 1. 0) 12. 2018 24
Member Constants � Member Variables with Constant Values ◦ Declared by const prefix ◦ No visibility declaration, treated as public ◦ Accessed from class using : : operator �By class name or by self identifier from within class Foo { const BAR = 42; function echo. Bar() { echo self: : BAR; } } echo Foo: : BAR; by Martin Kruliš (v 1. 0) 12. 2018 25
Static Members � Revision Static vs. Regular (Dynamic) Members static variable/constant Class static method new operator Object method Object member variable logically belongs to (is stored at) is used (called) on by Martin Kruliš (v 1. 0) 12. 2018 26
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 1. 0) 12. 2018 27
Static Members Example Only limited number of class Prescious { instances may exist const MAX_INSTANCES = 2; private static $instances = 0; public static function create() { if (self: : $instances < self: : MAX_INSTANCES) return new Foo(); else return null; } private function __construct() { ++self: : $instances; . . . } public function __destruct() { --self: : $instances; . . . } $foo 1 = Foo: : create(); $foo 2 = Foo: : create(); $foo 3 = Foo: : create(); $foo 3 is null by Martin Kruliš (v 1. 0) 12. 2018 28
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 1. 0) 12. 2018 29
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 1. 0) 12. 2018 30
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 1. 0) 12. 2018 31
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 1. 0) 12. 2018 32
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 1. 0) 12. 2018 33
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 1. 0) 12. 2018 34
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 1. 0) 12. 2018 35
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 1. 0) 12. 2018 36
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 ◦ Behavior of != and !== operators can be easily extrapolated by Martin Kruliš (v 1. 0) 12. 2018 37
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 1. 0) 12. 2018 38
OOP-Related Functions � Testing Existence ◦ class_exists(), interface_exists() ◦ method_exists() � Listings ◦ ◦ get_declared_classes(), get_declared_interfaces() get_class_methods() get_object_vars() get_class_vars() � Indirect Method Calls call_user_func_array($obj, 'method. Name'), $params); $name = 'method. Name'; $obj->$name(. . . $params) by Martin Kruliš (v 1. 0) 12. 2018 39
Autoloading � Automatic Loading of Classes ◦ Useful for libraries, reduces the number of includes ◦ Global function __autoload() �Called automatically when undeclared class is accessed function __autoload($class. Name) { if (file_exists("libs/$class. Name. php")) include_once "libs/$class. Name. php"; else log("Class $class. Name is not defined!"); } ◦ spl_autoload_register() �Register (possibly multiple) callback handler(s) by Martin Kruliš (v 1. 0) 12. 2018 40
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 1. 0) 12. 2018 41
Discussion by Martin Kruliš (v 1. 0) 12. 2018 42
- Slides: 42