Svetlin Nakov Technical Trainer Software University Object-Oriented Programming in PHP Classes, Class Members, OOP Principles.

Slides:



Advertisements
Similar presentations
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Advertisements

C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
AngularJS Routing Routes, Route Parameters, Templates, Location, Navigation SoftUni Team Technical Trainers Software University
PHP Flow Control Loops, Functions, Return, Exit, Require, Try...Catch Software University SoftUni Team Technical Trainers.
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
Advanced JavaScript Course Introduction SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
JavaScript Design Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers SoftUni.
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
OOP IN PHP `Object Oriented Programming in any language is the use of objects to represent functional parts of an application and real life entities. For.
Database APIs and Wrappers
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
Static Members and Namespaces Static Members, Indexers, Operators, Namespaces SoftUni Team Technical Trainers Software University
Controllers and Markup Controllers, $scope, Markup, Directives, Expressions, Binding, Filters, Validation SoftUni Team Technical Trainers Software University.
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
Using SQL Connecting, Retrieving Data, Executing SQL Commands, … Svetlin Nakov Technical Trainer Software University
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
Object-Oriented Programming in Java How Java Implements OOP: Classes, Objects, Exceptions, Etc. SoftUni Team Technical Trainers Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Technical Trainer Software University
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Code Formatting Correctly Formatting the Source Code Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
JavaScript Modules and Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers.
OOP Basic Topics Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Associative Arrays and Objects Associative Arrays, Objects Svetlin Nakov Technical Trainer Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Prototype Chain and Inheritance Prototype chain, Inheritance, Accessing Base Members Software University Technical Trainers SoftUni Team.
Events Event Handling in JavaScript SoftUni Team Technical Trainers Software University
Object-Oriented Programming Course Introduction Svetlin Nakov Technical Trainer Software University
Reflection Programming under the hood SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Simulating OOP in JavaScript Function Constructor, Prototypes, "this" Object, Classical and Prototypal Model Software University Technical.
Object-Oriented Programming in Java How Java Implements OOP: Classes, Objects, Exceptions, Etc. SoftUni Team Technical Trainers Software University
Design Patterns: Behavioral Design Patterns General and reusable solutions to common problems in software design Software University
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
PHP Exception Handling How to handle and create user-defined exceptions Mario Peshev Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
Loops, Methods, Classes Using Loops, Defining and Using Methods, Using API Classes, Exceptions, Defining Classes Svetlin Nakov Technical Trainer
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Static Members Static Variables & Methods SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Static Members and Namespaces
Abstract Classes, Abstract Methods, Override Methods
Classes, Properties, Constructors, Objects, Namespaces
Mocking tools for easier unit testing
Java OOP Overview Classes and Objects, Members and Class Definition, Access Modifier, Encapsulation Java OOP Overview SoftUni Team Technical Trainers.
Abstraction, Interface, Inheritance, Polymorphism, Override / Overload
Polymorphism, Interfaces, Abstract Classes
What is Encapsulation, Benefits, Implementation in Java
Java Programming Language
Classes and Objects Imran Rashid CTO at ManiWeber Technologies.
Presentation transcript:

Svetlin Nakov Technical Trainer Software University Object-Oriented Programming in PHP Classes, Class Members, OOP Principles and Practices in PHP

2 1.Classes in PHP1.Classes in PHP  Fields, Methods, Constructors, Constants, Access Modifiers, Encapsulation, Static Members 2.Interfaces and Abstract Classes2.Interfaces and Abstract Classes 3.Inheritance and Polymorphism3.Inheritance and Polymorphism 4.Traits4.Traits 5.Namespaces, Enumerations5.Namespaces, Enumerations 6.Error Levels, Exceptions6.Error Levels, Exceptions 7.Functional Programming7.Functional Programming Table of Contents

3 Classes in PHP class Laptop { private $model; private $price; public function __construct($model, $price) { $this->model = $model; $this->price = $price; } public function __toString() { return $this->model. " - ". $this->price. "lv."; } $laptop = new Laptop("Thinkpad T60", 320); echo $laptop; Fields Constructor Method $this-> points to instance members

4  Declared using the magic method __construct()  Automatically called when the object is initialized  Multiple constructors are not supported  Functions in PHP cannot be overloaded  Parent constructor is called using parent::__construct(…); inside function declaration Constructors in PHP function __construct($name, $age, $weight) { $this->name = $name; $this->name = $name; $this->age = $age; $this->age = $age; $this->weight = $weight; $this->weight = $weight;}

5 Constructors – Example class GameObject { private $id; private $id; function __construct($id) { $this->id= $id; function __construct($id) { $this->id= $id; }} class Player extends GameObject { private $name; private $name; function __construct($id, $name) { function __construct($id, $name) { parent::__construct($id); parent::__construct($id); $this->name = $name; $this->name = $name; }} Child class calls parent constructor

6  Access modifiers restrict the visibility of the class members  public – accessible from any class (default)  protected – accessible from the class itself and all its descendent classes  private – accessible from the class itself only Access Modifiers private $accountHolder; private $balance; public function __construct($accountHolder, $balance) { … } protected function accrueInterest($percent) { … }

7  Several ways of encapsulating class members in PHP:  Defining a separate getter and setter for each property: Encapsulation private $balance; function setBalance($newBalance) { if ($newBalance >= 0) { if ($newBalance >= 0) { $this->balance = $newBalance; $this->balance = $newBalance; } else { } else { trigger_error("Invalid balance"); trigger_error("Invalid balance"); }} function getBalance() { return $this->balance; return $this->balance;} Validates and sets the new value

8  Defining an universal getter and setter for all properties: Encapsulation (2) … public function __get($property) { public function __get($property) { if (property_exists($this, $property)) { if (property_exists($this, $property)) { return $this->$property; return $this->$property; } } public function __set($property, $value) { public function __set($property, $value) { if (property_exists($this, $property)) { if (property_exists($this, $property)) { $this->$property = $value; $this->$property = $value; } }} $myObj->name = "Asen"; echo $myObj->age; See

9  Functions in PHP:  Use camelCase naming  Can be passed to other functions as arguments (callbacks) Functions $array = array(2, 9, 3, 6, 2, 1); usort($array, "compareIntegers"); function compareIntegers($intA, $intB) { if ($intA == $intB) { if ($intA == $intB) { return 0; return 0; } return $intA > $intB ? 1 : -1; return $intA > $intB ? 1 : -1;}

10  Functions can be class members and can access $this Functions as Class Members class Laptop { private $model; private $model; private $price; private $price; public function __construct($model, $price) { public function __construct($model, $price) { $this->setModel($model); $this->setModel($model); $this->setPrice($price); $this->setPrice($price); } function calcDiscount($percentage) { function calcDiscount($percentage) { return $this->$price * $percentage / 100; return $this->$price * $percentage / 100; }}

11  PHP supports static class members  Declared using the static keyword  Accessed within the class with self:: / static:: Static Members class TransactionManager { private static $transactions = new Array(); private static $transactions = new Array(); … static function getTransaction($index) { static function getTransaction($index) { return self::$transactions[$index]; return self::$transactions[$index]; }}TransactionManager::getTransaction(4);

12  PHP supports two types of constant syntax  define($name, $value) – used outside class declaration  const – used inside a class declaration (declared static by default)  Constants are named in ALL_CAPS casing Constants define('MESSAGE_TIMEOUT', 400); class Message { const MESSAGE_TIMEOUT = 400; const MESSAGE_TIMEOUT = 400; …}

13  Interfaces in PHP:  Define the functions a class should implement  Can also hold constants  Implemented using the implements keyword  Can extend other interfaces Interfaces interface iCollection { function iterate(); function iterate();} interface iList extends iCollection { function add(); function add();}

14 Implementing an Interface – Example interface iResizable { function resize($x, $y); function resize($x, $y);} class Shape implements iResizable { private $x; private $x; private $y; private $y; function __construct() { function __construct() { $this->x = $x; $this->x = $x; $this->y = $y; $this->y = $y; } function resize($rX, $rY) { function resize($rX, $rY) { $this->x += $rX; $this->x += $rX; $this->y += $rY; $this->y += $rY; }}

15  Abstract classes:  Define abstract functions with no body  Cannot be instantiated  Descendant classes must implement the abstract functions Abstract Classes abstract class Employee { abstract function getAccessLevel(); abstract function getAccessLevel();} class SalesEmployee extends Employee { function getAccessLevel() { function getAccessLevel() { return AccessLevel::None; return AccessLevel::None; }}

16 Inheritance class Animal { private $name; private $name; private $age; private $age; function __construct($name, $age) { function __construct($name, $age) { $this->name = $name; $this->name = $name; $this->age = $age; $this->age = $age; }} class Dog extends Animal { private $owner; private $owner; function __construct($name, $age, $owner) { function __construct($name, $age, $owner) { parent::__construct($name, $age); parent::__construct($name, $age); $this->owner = $owner; $this->owner = $owner; }}

17  In PHP all class methods are virtual (unless declared final )  Can be overriden by child classes Virtual Methods class Shape { … public function rotate() { public function rotate() { … } public final move() { public final move() { … }} Can be overridden Cannot be overridden

18 Polymorphism abstract class Mammal { public function feed() { public function feed() { … }} class Dolphin extends Mammal { } class Human extends Mammal { } $mammals = Array(new Dolphin(), new Human(), new Human()); foreach ($mammals as $mammal) { $mammal->feed(); $mammal->feed();}

19  Forces method parameters to be of a certain class / interface  All subclasses / subinterfaces are also allowed  Works for classes, interfaces, arrays and callbacks (in PHP > 5.0)  Throws a fatal error if the types do not match Type Hinting function render(Shape $shape) { echo "Rendering the shape …"; echo "Rendering the shape …";} $triangle = new Triangle(); render($triangle);

20  Object type can be checked using the instanceof operator  Useful for ensuring the wrong class member will not be called Checking Object Type function takeAction(Person $person) { if ($person instanceof Student) { if ($person instanceof Student) { $person->learn(); $person->learn(); } else if ($person instanceof Trainer) { } else if ($person instanceof Trainer) { $person->train(); $person->train(); }}

21  Traits are groups of methods that can be injected in a class  Like interfaces but provide implemented functions, instead of function definitions Traits trait TalkTrait { public function sayHello() { public function sayHello() { echo "Hello!"; echo "Hello!"; } public function sayGoodbye() { public function sayGoodbye() { echo "Goodbye!"; echo "Goodbye!"; }}

22  Implemented with use inside class declaration  Implementing class and its children have access to trait methods Using Traits class Character { use TalkTrait; use TalkTrait; …} $character = new Character; $character->sayHello(); // function coming from TalkTrait $character->sayGoodbye(); // function coming from TalkTrait

23  PHP has no native enumerations  Possible workaround is declaring a set of constants in a class Enumerations class Month { const January = 1; const February = 2; const March = 3; …} $currMonth = Month::March; if ($currMonth Month::October) { echo "Damn it's cold!"; echo "Damn it's cold!";}

24  Namespaces group code (classes, interfaces, functions, etc.) around a particular functionality (supported in PHP > 5.3)  Declared before any other code in the file:  Accessing a namespace from another file: Namespaces namespace Calculations; function getCurrentInterest() {…} … use Calculations; $interest = Calculations\getCurrentInterest();

25 Namespaces – Example namespace NASA; include_once('Softuni.php'); use SoftUni; $topSoftUniStudent = SoftUni\getTopStudent(); echo $topSoftUniStudent; // Pesho Function call from SoftUni namespace namespace SoftUni; function getTopStudent() { return "Pesho"; return "Pesho";} File: Softuni.php File: NASA.php

26  PHP supports the try-catch-finally exception handling Exception Handling function divide($a, $b) { if ($b == 0) { if ($b == 0) { throw new Exception("Division by zero is not allowed!"); throw new Exception("Division by zero is not allowed!"); } return $a / $b; return $a / $b;} try { divide(4, 0); divide(4, 0); } catch (Exception $e) { echo $e->getMessage(); echo $e->getMessage();}

27  Exceptions hierarchy in Standard PHP Library (SPL): Exceptions Hierarchy in PHP

28 Creating Custom Exceptions class ENullArgumentException extends Exception { public function __construct() { public function __construct() { parent::__construct("Argument cannot be null.", 101); parent::__construct("Argument cannot be null.", 101); }} class Customer { function setName($name) { function setName($name) { if ($name == null) throw new ENullArgumentException(); if ($name == null) throw new ENullArgumentException(); else $this->name = $name; else $this->name = $name; }} try { $customer = new Customer(); $customer = new Customer(); $customer->setName("Gosho"); $customer->setName("Gosho"); } catch (ENullArgumentException $e) { echo $e->getMessage(). " / code: ". $e->getCode(); echo $e->getMessage(). " / code: ". $e->getCode();}

29  set_exception_handler($callback)  Executes $callback each time an exception is not handled  All uncaught exceptions are sent to this function Global Exception Handler set_exception_handler('ex_handler'); function ex_handler($e) { echo $e->getMessage(). " on line ". $e->getLine(); echo $e->getMessage(). " on line ". $e->getLine();}… throw new Exception("Random exception");

30  The magic __autoload() function attempts to load a class Auto Loading Classes class MyClass { public function __construct() { public function __construct() { echo "MyClass constructor called."; echo "MyClass constructor called."; }}./MyClass.class.php function __autoload($className) { include_once("./". $className. ".class.php"); include_once("./". $className. ".class.php");}… $obj = new MyClass(); // This will autoload MyClass.class.php./index.php

31  PHP has its standard library called SPL (Standard PHP Library)  Defines common collection interfaces  Defines some data structures like stacks, queue, heap, …  Defines iterators for arrays, directories, …  Defines standard exceptions class hierarchy  Defines standard autoload mechanism  Learn more about SPL at:  Standard PHP Library (SPL)

32  We can auto-load classes from PHP files the following way: SPL Auto Load define('CLASS_DIR', 'class/') set_include_path(get_include_path().PATH_SEPARATOR.CLASS_DIR);spl_autoload_extensions('.class.php');spl_autoload_register(); // This will load the file class/MyProject/Data/Student.class.php spl_autoload('\MyProject\Data\Student');

33  PHP provides several built-in array functions  Take array and callback (anonymous function) as arguments  Implement filtering and mapping in partially functional style: Functional Programming $numbers = array(6, 7, 9, 10, 12, 4, 2); $evenNumbers = array_filter($array, function($n) { return $n % 2 == 0; return $n % 2 == 0; }); $squareNumbers = array_map(function($n) { return $n * $n; return $n * $n; }, $evenNumbers);

Summary 1.PHP supports OOP: classes, fields, properties, methods, access modifiers, encapsulation, constructors, constants, static members, etc. 2.PHP supports interfaces and abstract classes 3.PHP supports inheritance and polymorphism 4.PHP supports traits: injecting a set of methods 5.PHP supports classical exception handling 6.PHP supports anonymous functions (callbacks) 34

? ? ? ? ? ? ? ? ? OOP in PHP

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 36  Attribution: this work may contain portions from  "OOP" course by Telerik Academy under CC-BY-NC-SA licenseOOPCC-BY-NC-SA

SoftUni Diamond Partners

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg