Objects and OO PHP

Dr Andres Baravalle

Objects and OO PHP

  • PHP primitive types
  • Object-oriented programming review
  • OO PHP
  • Advanced OOP functionality

PHP primitive types

PHP primitive types - review

So far we have seen how to use several of the primitive types supported by PHP:

Four scalar types (they can hold only one value at the time):

PHP primitive types - review (2)

There are also two compound types:

And two special types:

  • resource (we will see it in the next weeks)
  • NULL (a variable with no value)

empty, NULL and set/unset

  • A variable is empty if it does not exist or if its value equals FALSE
  • A variable is NULL when:
    • it has not been set to any value yet (or it has been unset)
    • it has been assigned the constant NULL
  • A variable is set if it is declared and not NULL

Comparisons of $x with PHP functions

Expression gettype() empty() is_null() isset() boolean
$x = ""; string TRUE FALSE TRUE FALSE
$x = array(); array TRUE FALSE TRUE FALSE
$x = false; boolean TRUE FALSE TRUE FALSE
$x = 0; integer TRUE FALSE TRUE FALSE
$x = "0"; string TRUE FALSE TRUE FALSE
$x = null; NULL TRUE TRUE FALSE FALSE
var $x;
$x is undefined

Comparisons of $x with PHP functions (2)

Expression gettype() empty() is_null() isset() boolean
$x = 1; integer FALSE FALSE TRUE TRUE
$x = -1;
$x = "1"; string FALSE FALSE TRUE TRUE
$x = "-1"; FALSE FALSE TRUE TRUE
$x = "php"; FALSE FALSE TRUE TRUE
$x = "true"; FALSE FALSE TRUE TRUE
$x = "false"; FALSE FALSE TRUE TRUE
$x = true; boolean FALSE FALSE TRUE TRUE

Object-oriented programming review

Object-oriented programming

Most modern programming languages use or require an object-oriented approach, which use objects and their relationships as a base for development.

You should be already quite familiar with the theoretical background of objects and the next slides will be focusing on PHP.

The next few slides are based on concepts from Britton & Doake, 2005. Please refer to the original source for more info.

Britton, J. and Doake, C. (2005) Software System Development: A Gentle Introduction. New York: McGraw-Hill.

Classes

Classes are data structures including attributes (constants and variables) and methods (functions).

Classes (2)

class is:

  • a description of objects that share the same attributes, methods, relationships and semantics.
  • a template for creating objects
  • a model of the the data and behavior that objects will have.

Objects

An object is an instance of a class.

What are objects?

Objects are like people. They’re living, breathing things that have knowledge inside them about how to do things and have memory inside them so they can remember things. [...]

Here’s an example: If I’m your laundry object, you can give me your dirty clothes and send me a message that says, “Can you get my clothes laundered, please.” I happen to know where the best laundry place in San Francisco is. And I speak English, and I have dollars in my pockets. So I go out and hail a taxicab and tell the driver to take me to this place in San Francisco. I go get your clothes laundered, I jump back in the cab, I get back here. I give you your clean clothes and say, “Here are your clean clothes.”

What are objects? (2)

You have no idea how I did that. You have no knowledge of the laundry place. Maybe you speak French, and you can’t even hail a taxi. You can’t pay for one, you don’t have dollars in your pocket. Yet I knew how to do all of that. And you didn’t have to know any of it. All that complexity was hidden inside of me, and we were able to interact at a very high level of abstraction. That’s what objects are. They encapsulate complexity, and the interfaces to that complexity are high level.

Steve Jobs, 2003

Working with classes

  1. Identify objects and derive classes from them
  2. Identify the attributes of classes
  3. Identify the methods on classes
  4. Identify relationship between classes
  5. Iterate and refine

Nouns, adjectives and verbs

The next slides use concepts that should be familiar to you: nouns, adjectives and verbs.

Noun: A word that refers to a person or thing, for example book, John, country, London, or friendship. Different types of noun include abstract, collective, countable/uncountable, concrete, gerund/verbal, mass, and proper.

Adjective: A word, such as heavyred, or sweet, that is used to describe (or modify) a noun.

Verb: A word that describes what a person or thing does, or what happens, for example run, sing, grow, occur, seem.

(from oxforddictionaries.com)

Identifying objects

  1. From the problem brief, note down every noun in each statement as potential object
  2. Study the list of objects and reject those that are unsuitable as classes:
    1. duplicates – different names for the same thing
    2. irrelevant – not part of the intended system
    3. vague or general - not with precise meaning or broad
    4. attributes – words representing values
    5. associations – words that represent relationships between objects (normally identifiable through expressions such as ‘part of’, ‘consists of’ or ‘is made up of’)
    6. roles – different roles for one basic entity
  3. From the remaining objects, derive classes

Identifying attributes

  1. From the problem brief, note down:
    1. Phrases such as “the number of members of staff” or adjectival phrases, such as “student number”.
    2. Reject attributes which can be derived from others.
  2. Then, reduce the number of classes; if two classes have the same or similar attributes, see if the concept could be represented using one class only (or using inheritance - more in the next slides).

Bicycle rental example

You have been tasked to create web based software for bicycle rental; you must:

  • Keep a complete list of all bicycles and their details including type, size, make, model, daily charge rate, deposit
  • Keep a record of all customers and their past hire transactions
  • Work out automatically how much it will cost to hire a given bicycle for a given number of days
  • Record the details of a hire transaction including the start date, estimated duration, customer and bicycle
  • Work out automatically, on the return of a bicycle, how long it was hired for, how many days were originally paid for, how much extra is due
  • Record the total amount due and how much has been paid
  • Print a receipt for each customer
  • Keep track of the state of each bicycle, e.g. whether it is in stock, hired out or being repaired

Bicycle rental example (2)

We have now to identify objects, attributes and methods - we will use the method outlined in the previous slides to identify potential objects, attributes and methods.

Bicycle rental example: finding nouns

You have been tasked to create web based software for bicycle rental; you must:

  • Keep a complete list of all bicycles and their details including type, size, make, model, daily charge rate, deposit
  • Keep a record of all customers and their past hire transactions
  • Work out automatically how much it will cost to hire a given bicycle for a given number of days
  • Record the details of a hire transaction including the start date, estimated duration, customer and bicycle
  • Work out automatically, on the return of a bicycle, how long it was hired for, how many days were originally paid for, how much extra is due
  • Record the total amount due and how much has been paid
  • Print a receipt for each customer
  • Keep track of the state of each bicycle, e.g. whether it is in stock, hired out or being repaired

Show the nouns

p>

Bicycle rental example: finding nouns (2)

  • bicycles
  • list (of bicycles)
  • details (of bicycles)
  • type
  • size
  • make
  • model
  • charge rate
  • deposit
  • record (of all customers)
  • customers
  • hire transactions
  • number of days
  • start date
  • duration
  • return
  • days (originally paid for)
  • extra (money due)
  • amount (due)
  • (amount paid)
  • receipt
  • state (of each bicycle)

Bicycle rental example: removing duplicate and irrelevant nouns

  • duplicates: already removed
  • irrelevant: none

Bicycle rental example: removing vague nouns

  • bicycles
  • list (of bicycles)
  • details (of bicycles)
  • type
  • size
  • make
  • model
  • charge rate
  • deposit
  • record (of all customers)
  • customers
  • hire transactions
  • number of days
  • start date
  • duration
  • return
  • days (originally paid for)
  • extra (money due)
  • amount (due)
  • (amount paid)
  • receipt
  • state (of each bicycle)

Bicycle rental example: removing attributes

We'll now exclude words representing values - they are going to be the attributes of our classes.

  • bicycles
  • list (of bicycles)
  • details (of bicycles)
  • type
  • size
  • make
  • model
  • charge rate
  • deposit
  • record (of all customers)
  • customers
  • hire transactions
  • number of days
  • start date
  • duration
  • return
  • days (originally paid for)
  • extra (money due)
  • amount (due)
  • (amount paid)
  • receipt
  • state (of each bicycle)

Bicycle rental example: removing associations and roles

No roles or associations - if we were renting cars we could have driver/passenger roles.

Bicycle rental example: objects

We have identified 3 type of objects:

  • bicycles
  • customers
  • (hire) transactions

In more complex systems further refining might be needed - in this case they are clearly diverse and unrelated, so we can create a class for each of the objects that we have identified.

Identifying methods

  1. From the problem brief, note down predicates, as "create an id" or "change the account" (they must include a verb)
  2. Study the list of predicates and reject those that are unsuitable as methods:
    1. duplicates – different names for the same thing
    2. irrelevant – not part of the intended system
    3. vague or general - not with precise meaning or broad
    4. associations – verbs that represent relationships between objects (normally identifiable through expressions such as ‘part of’, ‘consists of’ or ‘is made up of’)
  3. From the remaining predicates, derive the methods

Bicycle rental example: finding verbs

You have been tasked to create web based software for bicycle rental; you must:

  • Keep a complete list of all bicycles and their details including type, size, make, model, daily charge rate, deposit
  • Keep a record of all customers and their past hire transactions
  • Work out automatically how much it will cost to hire a given bicycle for a given number of days
  • Record the details of a hire transaction including the start date, estimated duration, customer and bicycle
  • Work out automatically, on the return of a bicycle, how long it was hired for, how many days were originally paid for, how much extra is due
  • Record the total amount due and how much has been paid
  • Print a receipt for each customer
  • Keep track of the state of each bicycle, e.g. whether it is in stock, hired out or being repaired

Bicycle rental example: analysing verbs

As the example is quite basic, most verbs will be methods:

Verb Method name
Keep (a complete list) will use an array of bicycle objects
Keep a record of all customers will use an array of customer objects
Work out (automatically how much it will cost) quote()
Record save() (or the constructor)
Print print()
Keep track status()

Activity #1: Module registration

The following problem brief describes the (simplified) requirements for module registration.

Each student in the school is identified by name, surname, student id. Full time students can register up to 150 credits per year, and a minimum of 90. Part time students can register 15 to 60 credits per year.

A degree is composed by 360 credits; all modules are options and are identified as "Module1"..."Module 30".

Modules can have 15 or 30 credits:

  • Modules from 1 to 25: 15 credits
  • Modules 26-30: 30 credits

Using the methodology explained in the previous pages, please identify classes, attributes, methods and the relationship between the classes.

Activity #2

Please note that the activities for this week are sequential - you must have succeeded in Activity #1 to engage with Activity #2.

Please have your tutor check your activities in class.

Building on top of activity #1, please write a case diagram (using UML).

OO PHP

OO features in PHP

The next slides will focus on the object-oriented features implemented in PHP.

Among the features in PHP 5 are:

We will cover some of these topics in class.

You will have to study the remaining ones from the text book and the PHP documentation.

Structure of a class

Basic class definitions begin with the keyword class, followed by a class name and a pair of curly braces:

<?php
class Staff {
            
}
?>            

The class name can be any valid label which is not a PHP reserved word. Good coding practice recommends you define each class in a separate file, including the class only (and no procedural coding).

A class may contain its own constantsvariables (called "properties" or "attributes") and functions (called "methods").

Structure of a class: attributes

To be useful, a class needs its attributes. Attributes are created within the class definition using keywords that match the visibility of the variable: public, private or protected. We will learn more about visibility in the next slides.


<?php
class Staff {
	public $name; 
	public $surname;
}
?>

Activity #3: classes and attributes

Building on top of the previous activities, please write the PHP code for your classes and attributes.

Structure of a class: methods

You create methods by declaring functions within the class definition:


<?php
class Staff {
	private $staff_id; 
  
	function getStaffId() {
		    return $this->staff_id; 
	}
}
?>

Structure of a class: constructors

A constructor is a special ("magic") method that is called when an object is created. It's normally used to perform initialisation tasks.


<?php
class Staff {

	private $name; 
	private $surname;
	private $staff_id; 
	private $contact_number;

	function __construct($name, $surname, $staff_id, $contact_number) {
            // $this does have a special meaning - we will explain it in a few slides
            $this->name = $name;
            $this->surname = $surname;
            $this->staff_id = $staff_id; 
            $this->contact_number = $contact_number;
	}
}
?>

Activity #4: methods and constructor stubs

Building on top of activities #1, #2 and #3, write a stub for your methods and constructors (write the function names and parameters, but do not develop the code inside your functions).

Some suggestions/directions:

  • A student can only take modules that exist ("Module 1" ... "Module 30")
  • You should check that the total number of credits is valid
  • Do not worry about removing modules at this stage - just adding modules

Structure of a class: destructors

A destructor is a special method (__destruct()) that is called as soon as there are no other references to a particular object.

Its use will depend from implementation circumstances, but it's typically used to terminate resources that are open (e.g. database connections and file handles).

When is it needed? Please read both your textbook and this stackoverflow discussion!

Instantiating classes

To use a class, you need to create an object as an instance of the class that you have defined.

Objects are created with the keyword new, followed by the class name, round brackets and any parameters required by the constructor.


<?php
$andres = new Staff("Andres", "Baravalle", "0123456", "01234567"); 
?>

Instantiating classes (2)


<?php
print_r($andres);

/*
Staff Object
(
    [name] => Andres
    [surname] => Baravalle
    [staff_id] => 0123456
    [contact_number] => 01234567
)
*/

?>

Activity #5: creating new objects

Building on top of activities #1-#4, please create:

  • One object per module (you may need a loop)
  • At least 6 different students, each registering their modules

Review the previous steps as needed; at this stage your functions are still stubs.

For this and the next activities, use either print_r() or your editor's features to debug as needed.

Accessing class attributes (from the class)

Within a class, you have access to a special variable called $this.

$this is used to refer to the attributes in the class. If an attribute in your class is called $attribute1, within your class you refer to it as $this->attribute1.

We have already seen the $this variable in our constructor.

Accessing class attributes (from the object)

You can also access class attributes from your object. If your object is called $andres and your (public) attribute is $attribute1, you can refer to it from your object as $andres->attribute1.


<?php
$andres->name = "Andres Nicolas"; 
?>

Using class methods

Within a class, you can also use the $this keyword to call the class methods defined within the class.

<?php

class Staff {
	function staff1() {
		// do something and then call staff2()
		$this->staff2();
	}

	function staff2() {
		// do something
	}
}
?>

Activity #6: writing your methods and constructors

Building on top of activities #1-#5, please complete the development of your methods and constructors.

Controlling access

PHP supports 3 different access modifiers for attributes and methods:

  • public: for items that should be accessed from inside the class (e.g. using $this) and from outside (e.g. using the $objectname->attributename syntax)
  • protected: for items that should be accessed from inside the class itself and by inherited and parent classes
  • private: for items that should be accessed only from inside the class. Items that are private will not be inherited (we'll see more later on)

Controlling access (2)

Access modifiers can be used both on attributes and methods.

Class example: storing staff data

<?php

class Staff {
	// accessed everywhere
	public $name; 
	public $surname;
  
	// accessed only within the class/inherited classes/parent class
	protected $staff_id; 
  
	// accessed only within the class
	private $contact_number;

    // will run when a new object is created
	function __construct($name, $surname, $staff_id, $contact_number) {
		$this->name = $name;
		$this->surname = $surname;
		$this->staff_id = $staff_id; 
		$this->contact_number = $contact_number;
	}
  
	public function getStaffId() {
		return $this->staff_id; 
	}
}

$andres = new Staff("Andres", "Baravalle", "0123456", "01234567"); 
echo $andres->name; // ok
echo $andres->surname; // ok
echo $andres->staff_id; // no!
echo $andres->contact_number; // no!
echo $andres->getSstaffId(); // yes
?>

Activity #7: using getters and setters

Building on top of Activities #1-#6, set the visibility of your variables and write getters/setters:

  • name, surname and student id should be represented as public variables
  • Add $disability_notes as private variable
  • write "getter" functions (getDisabilityNotes()) to get the value of $disability_notes
  • write "setter" functions for $disability_notes

Demonstrate the use of the functions that you have created by created instances of your classes and invoking the new methods through your objects.

Implementing inheritance

You can use the keyword extends to identify a class as a subclass (extension) of another.

The extended or derived class has all variables and functions of the base class (this is called 'inheritance') and what you add in the extended definition.

Implementing inheritance: users and staff

<?php
class Users {

	function __construct($name, $surname, $user_id) {
		// initialisation code here
	}
}

class Staff extends Users {

	public $contact_number; // this variable is not present in the Users class
}
?>    

Implementing inheritance: overriding

Subclasses can declare new functions and attributes, but can also redeclare (override) some attributes and functions of their parent class.

Implementing inheritance: users and staff

<?php
class Users {

	function __construct($name, $surname, $user_id) {
		// initialisation code here
	}
}

class Staff extends Users {

	public $contact_number;
	
	// the class Staff needs a specific method to create staff users 
	function __construct($name, $surname, $user_id, $contact_number) {
		// initialisation code here
		// uncomment the next line if you need to call the parent constructor too
		// parent::__construct($name, $surname, $user_id)
	}
}
?>

Activity #8: part-time and full-time student classes

Re-engineer your code to have a "Student" superclass and two sub-classes, part-time and full-time. Implement inheritance appropriately (e.g. ensure that a student is registering the right amount of credits).

Create 2 new part-time and 2 new full-time objects.

Advanced OO functionalities

Class constants, static attributes and methods, abstract classes and interfaces

In the next slides we are going to look at advanced OO functionalities.

Class constants

PHP supports class constants:

<?php
class Staff {

	function __construct($name, $surname, $user_id, $contact_number) {
		// initialisation code here
	}
}

class UelStaff extends Staff {
	
	const organisation = "University of East London";
}
?>    

Static attributes and methods

Up to now, you have created objects from your classes, and you have been using the methods and attributes defined in your classes.

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).

PHP includes some special class name, parent, which refers to the parent class.

Static attributes and methods example

<?php

class Rectangle {
	static function calculateArea($a, $b) {
		// code here
	}
}

$area = Rectangle::calculateArea(5, 6);
?>

Abstract classes

PHP allows to user abstract classes and methods. Abstract classes contain one or more abstract methods.

Abstract methods include just a basic "signature" and are defined appropriately in classes extending the abstract class.

In PHP, abstract classes and methods are introduced by the keyword abstract.

Abstract classes: example

<?php
abstract class Polygon {
 public function doSomething() {
    echo "<p>This function does something.</p>";
    }
 abstract public function getArea();
} 

class Rectangle extends Polygon
    {
    public function getArea() {
    $this->area = $this->base * $this->height;
    return $this->area;
    }
    
    function __construct($a, $b) {
    $this->base = $a;
    $this->height = $b;
    }
}
$rectangle = new Rectangle(4, 6);
echo $rectangle->getArea();
?>
                        

Multiple inheritance

Some programming languages do support multiple inheritance.

Multiple inheritancy diagram

Interfaces

PHP does not support multiple inheritance, but does support the use of interfaces (see this stackoverflow thread and Wikipedia for more on the rationale behind it).

Interfaces can be used as a way to better structure your code when complex relationships between classes come to play.

Interfaces in PHP

Interfaces are used to detail which methods a class must implement, without having to define how these methods are handled.

Interfaces are defined using the interface keyword, but without any of the methods having their contents defined.

All methods declared in an interface must be public.

Using interfaces

<?php
// please note that classes and interfaces should each be on its own file
// this is to improve readability and maintainability

class Users {
	// more code here
}

interface StorageInterface() {
	public function saveData();
	public function retrieveData();
}

class Staff extends Users implements StorageInterface {
	// more code here

	public function saveData() {
		// code here
	}

	public function retrieveData() {
		// code here
	}	
}
?>

Activity #9: interfaces

Update:

  • your code to include a PrintData interface; this will declare a printData() function
  • your classes, to implement the PrintData interface.

Implement the printData() function in your classes to print the public variables for the object, as a table.

Interfaces vs Classes

It is useful to think of classes as an is-a relationship and interfaces as features not necessarily inherited.

Example: class Mammal extends Animal implements HasLegs

Interfaces vs Abstract Classes

With interfaces, all the methods declared in the interface must be defined in the class implementing the interface. No methods are defined in the interface.

With abstract classes, methods can be defined in the abstract class (not just declared); abstract methods must be defined in the class extending the abstract class.

This work

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License

Creative Commons License