PHP Object Oriented Programming (OOP) Dr. Charles Severance www.php-intro.com.

Slides:



Advertisements
Similar presentations
Understand and appreciate Object Oriented Programming (OOP) Objects are self-contained modules or subroutines that contain data as well as the functions.
Advertisements

Object-Oriented Programming Basics Prof. Ankur Teredesai, Computer Science Department, RIT.
Introduction to PHP Dr. Charles Severance
PHP Functions / Modularity
JavaScript Functions, Objects, Array, and Control Structures Dr. Charles Severance
OBJECT ORIENTED PROGRAMMING M Taimoor Khan
Classes & Objects Computer Science I Last updated 9/30/10.
OBJECT-ORIENTED PROGRAMMING CONCEPTS (Review). What is an Object? What is an Object? Objects have states and behaviors. Example: A dog has states - color,
ITEC200 – Week03 Inheritance and Class Hierarchies.
Object-Oriented PHP (1)
OOP & JAVA. HelloWorld.java /** * The HelloWorld class is an application that * displays "Hello World!" to the standard output. */ public class HelloWorld.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Getting PHP Hosting Dr. Charles Severance. What We Need We want to be able to put up our application on the web so anyone can access our URL (and so we.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 An Introduction to Visual Basic Objectives Explain the history of programming languages Define the terminology used in object-oriented programming.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
+ Java vs. Javascript Jessi Style. + Java Compiled Can stand on its own Written once, run anywhere Two-stage debugging Java is an Object Oriented Programming.
UFCEUS-20-2 : Web Programming Lecture 5 : Object Oriented PHP (1)
Programming Languages and Paradigms Object-Oriented Programming.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Introduction to Object-oriented programming and software development Lecture 1.
An Object-Oriented Approach to Programming Logic and Design
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
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.
Object-Oriented Programming. An object is anything that can be represented by data in a computer’s memory and manipulated by a computer program.
1 Programming Paradigms Object Orientated Programming Paradigm (OOP)
Conditional Execution Chapter 3 Python for Informatics: Exploring Information
Object-Oriented Programming with Java Lecture 1: Introduction Autumn, 2007.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
David Lawrence 7/8/091Intro. to PHP -- David Lawrence.
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 12 Object-Oriented Programming Starting Out with Games & Graphics.
PHP Functions Dr. Charles Severance
Introduction to Object-Oriented Programming Lesson 2.
Introduction to OOP CPS235: Introduction.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Basic Concepts of OOP.  Object-Oriented Programming (OOP) is a type of programming added to php5 that makes building complex, modular and reusable web.
PHP Functions / Modularity Dr. Charles Severance
OOP Basics Classes & Methods (c) IDMS/SQL News
PHP Functions Chapter 5 Dr. Charles Severance To be used in association with the book: PHP, MySql, and JavaScript by Robin Nixon.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Mr H Kandjimi 2016/01/03Mr Kandjimi1 Week 3 –Modularity in C++
CPS120: Introduction to Computer Science Lecture 16A Object-Oriented Concepts.
What is an object?. What Makes an Object? An object has identity (it acts as a single whole). Every object has a name that identifies what it is. Ex.
Object-oriented programming (OOP) is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their.
Python Objects Charles Severance Python for Everybody
Introduction to Object-oriented Programming
Visit for more Learning Resources
Objects as a programming concept
PHP Functions / Modularity
Object-Oriented Programming Basics
PHP Object Oriented Programming (OOP)
HTTP Parameters and Arrays
Functions Chapter 4 Python for Everybody
PRINCIPALES OF OBJECT ORIENTED PROGRAMMING
Object Oriented Programming in JavaScript
PHP Namespaces (in progress)
More Object-Oriented Programming
Object-Oriented Programming in PHP
Object-Oriented PHP (1)
CPS120: Introduction to Computer Science
Classes and Objects Imran Rashid CTO at ManiWeber Technologies.
C++ Object Oriented 1.
Presentation transcript:

PHP Object Oriented Programming (OOP) Dr. Charles Severance

PHP => Object Oriented WIth PHP 5, an object oriented approach is the preferred pattern Libraries are evolving toward OOP

Object Oriented Programming (OOP) Object-oriented programming (OOP) is a programming paradigm that represents concepts as "objects" that have data fields (attributes that describe the object) and associated procedures known as methods. Objects, which are usually instances of classes, are used to interact with one another to design applications and computer programs.

Definitions Class - a template - Dog Method - A defined capability of a class - bark() Object or Instance - A particular instance of a class - Lassie

Terminology: Class Defines the abstract characteristics of a thing (object), including the thing's characteristics (its attributes, fields or properties) and the thing's behaviors (the things it can do, or methods, operations or features). One might say that a class is a blueprint or factory that describes the nature of something. For example, the class Dog would consist of traits shared by all dogs, such as breed and fur color (characteristics), and the ability to bark and sit (behaviors).

Terminology: Class A pattern (exemplar) of a class. The class of Dog defines all possible dogs by listing the characteristics and behaviors they can have; the object Lassie is one particular dog, with particular versions of the characteristics. A Dog has fur; Lassie has brown-and-white fur.

Terminology: Instance One can have an instance of a class or a particular object. The instance is the actual object created at runtime. In programmer jargon, the Lassie object is an instance of the Dog class. The set of values of the attributes of a particular object is called its state. The object consists of state and the behavior that's defined in the object's class. Object and Instance are often used interchangeably.

Terminology: Method An object's abilities. In language, methods are verbs. Lassie, being a Dog, has the ability to bark. So bark() is one of Lassie's methods. She may have other methods as well, for example sit() or eat() or walk() or save_timmy(). Within the program, using a method usually affects only one particular object; all Dogs can bark, but you need only one particular dog to do the barking Method and Message are often used interchangeably.

Non-OOP

OOP

<?php date_default_timezone_set('America/New_York'); $nextWeek = time() + (7 * 24 * 60 * 60); echo 'Now: '. date('Y-m-d')."\n"; echo 'Next Week: '. date('Y-m-d', $nextWeek)."\n"; echo("=====\n"); $now = new DateTime(); $nextWeek = new DateTime('today +1 week'); echo 'Now: '. $now->format('Y-m-d')."\n"; echo 'Next Week: '. $nextWeek->format('Y-m-d')."\n"; Now: Next Week: ===== Now: Next Week: date.php

Making a Class / Objects

<?php $chuck = array("fullname" => "Chuck Severance", 'room' => '4429NQ'); $colleen = array("familyname" => "van Lent", 'givenname' => 'Colleen', 'room' => '3439NQ'); function get_person_name($person) { if ( isset($person['fullname']) ) return $person['fullname']; if ( isset($person['familyname']) && isset($person['givenname']) ) { return $person['givenname']. ' '. $person['familyname'] ; } return false; } print get_person_name($chuck). "\n"; print get_person_name($colleen). "\n"; Chuck Severance Colleen van Lent nonobj.php

<?php class Person { public $fullname = false; public $givenname = false; public $familyname = false; public $room = false; function get_name() { if ( $this->fullname !== false ) return $this->fullname; if ( $this->familyname !== false && $this->givenname !== false ) { return $this->givenname. ' '. $this->familyname; } return false; } $chuck = new Person(); $chuck->fullname = "Chuck Severance"; $chuck->room = "4429NQ"; $colleen = new Person(); $colleen->familyname = 'van Lent'; $colleen->givenname = 'Colleen'; $colleen->room = '3439NQ'; print $chuck->get_name(). "\n"; print $colleen->get_name(). "\n"; Chuck Severance Colleen van Lent withobj.php

Reading Documentation

echo DateTime::RFC822."\n"; D, d M y H:i:s O

$x = new DateTime(); $y = new DateTime('now'); $z = new DateTime(' ');

$x = new DateTime(' '); $oops = DateTime::getLastErrors(); print_r($oops); Array ( [warning_count] => 1 [warnings] => Array ( [11] => The parsed date was invalid ) [error_count] => 0 [errors] => Array ( )

$z = new DateTime(' '); echo $z->format('Y-m-d')."\n";

Object Life Cycle

Object Life Cycle Objects are created, used and discarded We have special blocks of code (methods) that get called At the moment of creation (constructor) At the moment of destruction (destructor) Constructors are used a lot Destructors are seldom used

Constructor The primary purpose of the constructor is to set up some instance variables to have the proper initial values when the object is created

class PartyAnimal { function __construct() { echo("Constructed\n"); } function something() { echo("Something\n"); } function __destruct() { echo("Destructed\n"); } echo("--One\n"); $x = new PartyAnimal(); echo("--Two\n"); $y = new PartyAnimal(); echo("--Three\n"); $x->something(); echo("--The End?\n"); --One Constructed --Two Constructed --Three Something --The End? Destructed party.php

Many Instances We can create lots of objects - the class is the template for the object We can store each distinct object in its own variable We call this having multiple instances of the same class Each instance has its own copy of the instance variables

class Hello { protected $lang; // Only accessible in the class function __construct($lang) { $this->lang = $lang; } function greet() { if ( $this->lang == 'fr' ) return 'Bonjour'; if ( $this->lang == 'es' ) return 'Hola'; return 'Hello'; } $hi = new Hello('es'); echo $hi->greet()."\n"; Hola hello.php

Definitions Class - a template - Dog Method or Message - A defined capability of a class - bark() Object or Instance - A particular instance of a class - Lassie Constructor - A method which is called when the instance / object is created

Inheritance

Inheritance When we make a new class - we can reuse an existing class and inherit all the capabilities of an existing class and then add our own little bit to make our new class Another form of store and reuse Write once - reuse many times The new class (child) has all the capabilities of the old class (parent) - and then some more

Terminology: Inheritance ‘Subclasses’ are more specialized versions of a class, which inherit attributes and behaviors from their parent classes, and can introduce their own.

class Hello { protected $lang; function __construct($lang) {... } function greet() {... } } class Social extends Hello { function bye() { if ( $this->lang == 'fr' ) return 'Au revoir'; if ( $this->lang == 'es' ) return 'Adios'; return 'goodbye'; } $hi = new Social('es'); echo $hi->greet()."\n"; echo $hi->bye()."\n"; Hola Adios goodbye.php

Definitions Class - a template - Dog Method or Message - A defined capability of a class - bark() Object or Instance - A particular instance of a class - Lassie Constructor - A method which is called when the instance / object is created Inheritance - the ability to take a class and extend it to make a new class.

Visibility Class member variables also have scope Public – can be accessed outside the class, inside the class, and in derived classes Protected – can be accessed inside the class, and in derived classes Private – can be accessed inside the class (i.e. private variables are not visible in derived classes)

class MyClass { public $pub = 'Public'; protected $pro = 'Protected'; private $priv = 'Private'; function printHello() { echo $this->pub."\n"; echo $this->pro."\n"; echo $this->priv."\n"; } $obj = new MyClass(); echo $obj->pub."\n"; // Works echo $obj->pro."\n"; // Fatal Error echo $obj->priv."\n"; // Fatal Error $obj->printHello(); // Shows Public, Protected and Private Public Protected Private visibility.php

class MyClass2 extends MyClass { function printHello() { echo $this->pub."\n"; echo $this->pro."\n"; echo $this->priv."\n"; // Undefined } echo("--- MyClass2 ---\n"); $obj2 = new MyClass2(); echo $obj2->pub."\n"; // Works $obj2->printHello(); // Shows Public, Protected, Undefined --- MyClass2 --- Public Protected (false)

Building an Object from Scratch Sometimes a developer will prefer to make an object with public key-value pairs rather than an array Use where appropriate..

$player = new stdClass(); $player->name = "Chuck"; $player->score = 0; $player->score++; print_r($player); class Player { public $name = "Sally"; public $score = 0; } $p2 = new Player(); $p2->score++; print_r($p2); stdClass Object ( [name] => Chuck [score] => 1 ) Player Object ( [name] => Sally [score] => 1 ) scratch.php

Namespaces and Frameworks

PHP has many "Frameworks" There are many PHP Frameworks with large code bases Each framework cannot define a global function called "setup" or they would overwrite each other We need a naming convention to keep these large code bases from stepping on each other so that applications can use more than one framework

PHP-FIG Standards What to name classes and where to place them in the source directory How to properly namespace classes to avoid collission

OO In Frameworks OO allows us to avoid clashes for global function names $date = DateTime::createFromFormat('j-M-Y', '15-Feb-2009'); We also want to avoid clashes on class names as well

Name Spaces The PHP namespace directive lets us "silo" all of our classes in a file within a global "namespace" <?php namespace Tsugi\Core; class User {... $d = new \DateTime('today +1 week') } tsugi/lib/vendor/Tsugi/Core/User.php Fully-qualified class name: \Tsugi\Core\User

Accessing a Class in a Namespace To get the class we want – we must indicate which the name space we want <?php... $USER = new \Tsugi\Core\User(); tsugi/lib/vendor/Tsugi/Core/LTIX.php <?php use \Tsugi\Core\User; $USER = new User();

Auto Loader for Classes Normally we put class definition in files and then include them do the classes are defined for our code tsugi/lib/lms_lib.php <?php... require_once("vendor/Tsugi/Core/User.php"); require_once("vendor/Tsugi/Core/Context.php"); require_once("vendor/Tsugi/Core/Link.php"); require_once("vendor/Tsugi/Core/LTIX.php");...

Auto Loader for Classes With large PHP frameworks like Symfony, we may have many hundreds of classes that are used very rarely PHP has the ability to auto-load classes when code tries to "new" a class that is not yet loaded But standards are needed because it is best if there is one autoloader across all frameworks

Folder and Class Naming So that PHP auto loaders can be interoperable, there are rules about class names and folder names and you are only supposed to put one class in a file \Tsugi\Core\Usertsugi/lib/vendor/Tsugi/Core/User.php \Tsugi\Core\Contexttsugi/lib/vendor/Tsugi/Core/Context.php \Tsugi\Core\Settingstsugi/lib/vendor/Tsugi/Core/Settings.php

Summary Object Oriented programming is a very structured approach to code reuse. There is a trend away from global function names and toward OO We can group data and functionality together and create many independent instances of a class There is a trend away from global class names and toward namespaces and namespace conventions

Acknowledgements / Contributions These slides are Copyright Charles R. Severance ( as part of and made available under a Creative Commons Attribution 4.0 License. Please maintain this last slide in all copies of the document to comply with the attribution requirements of the license. If you make a change, feel free to add your name and organization to the list of contributors on this page as you republish the materials. Initial Development: Charles Severance, University of Michigan School of Information Insert new Contributors and Translators here including names and dates Continue new Contributors and Translators here