Andres Baravalle
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):
There are also two compound types:
And two special types:
Expression | gettype() | empty() | is_null() | isset() | boolean : if($x) |
---|---|---|---|---|---|
$x = ""; | string | TRUE | FALSE | TRUE | FALSE |
$x = array(); | array | ||||
$x = false; | boolean | ||||
$x = 0; | integer | ||||
$x = "0"; | string | ||||
$x = null; | NULL | TRUE | TRUE | FALSE | FALSE |
var $x; | |||||
$x is undefined |
Expression | gettype() | empty() | is_null() | isset() | boolean : if($x) |
---|---|---|---|---|---|
$x = 1; | integer | FALSE | FALSE | TRUE | TRUE |
$x = -1; | |||||
$x = "1"; | strings | ||||
$x = "-1"; | |||||
$x = "php"; | |||||
$x = "true"; | |||||
$x = "false"; | |||||
$x = true; | boolean |
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 are data structures including attributes (constants and variables) and methods (functions).
A class is:
An object is an instance of a class.
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.”
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.
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 heavy, red, 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)
You have been tasked to create web based software for bicycle rental; you must:
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.
You have been tasked to create web based software for bicycle rental; you must:
Show the nouns
p>
|
|
|
|
|
|
|
|
We'll now exclude words representing values - they are going to be the attributes of our classes.
|
|
|
|
No roles or associations - if we were renting cars we could have driver/passenger roles.
We have identified 3 type of objects:
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.
You have been tasked to create web based software for bicycle rental; you must:
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() | |
Keep track | status() |
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:
Using the methodology explained in the previous pages, please identify classes, attributes, methods and the relationship between the classes.
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).
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.
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 constants, variables (called "properties" or "attributes") and functions (called "methods").
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;
}
?>
Building on top of the previous activities, please write the PHP code for your classes and attributes.
You create methods by declaring functions within the class definition:
<?php
class Staff {
private $staff_id;
function getStaffId() {
return $this->staff_id;
}
}
?>
A constructor is a special 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;
}
}
?>
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 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!
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");
?>
<?php
print_r($andres);
/*
Staff Object
(
[name] => Andres
[surname] => Baravalle
[staff_id] => 0123456
[contact_number] => 01234567
)
*/
?>
Building on top of activities #1-#4, please create:
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.
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.
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";
?>
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
}
}
?>
Building on top of activities #1-#5, please complete the development of your methods and constructors.
PHP supports 3 different access modifiers for attributes and methods:
$this
) and from outside (e.g. using the $objectname->attributename
syntax)Access modifiers can be used both on attributes and methods.
<?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
?>
Building on top of Activities #1-#6, set the visibility of your variables and write getters/setters:
$disability_notes
as private variable getDisabilityNotes()
) to get the value of $disability_notes
$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.
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.
<?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
}
?>
Subclasses can declare new functions and attributes, but can also redeclare (override) some attributes and functions of their parent class.
<?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)
}
}
?>
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.
In the next slides we are going to look at advanced OO functionalities.
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";
}
?>
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.
<?php
class Rectangle {
static function calculateArea($a, $b) {
// code here
}
}
$area = Rectangle::calculateArea(5, 6);
?>
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
.
<?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();
?>
Some programming languages do support multiple inheritance.
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 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.
<?php
// please note that under number circumstances 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
}
}
?>
Update:
PrintData
interface; this will declare a printData()
functionPrintData
interface.Implement the printData()
function in your classes to print the public variables for the object, as a table.
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
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 is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License