COMP284 Scripting Languages
Lecture 8: PHP (Part 6)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
1 Classes
Defining and Instantiating a Class
Visibility
Class Constants
Static Properties and Methods
Destructors
Inheritance
Interfaces
Introspection Functions
COMP284 Scripting Languages Lecture 8 Slide L8 1
Classes Defining and Instantiating a Class
Defining and Instantiating a Class
PHP is an object-oriented language with classes
A class can be defined as follows:
class iden tifi er {
pro pe rty _defi nit io ns
fun ct ion _defi nit io ns
}
The class name identifier is case-sensitive
The body of a class consists of property definitions and function definitions
The function definitions may include the definition of a constructor
An object of a class is created using
new ide ntif ier ( arg1 ,arg2 ,...)
where arg1,arg2,... is a possibly empty list of arguments passed to
the constructor of the class identifier
COMP284 Scripting Languages Lecture 8 Slide L8 2
Classes Defining and Instantiating a Class
A Closer Look at Class Definitions
In more detail, the definition of a class
typically looks as follows
class iden tifi er {
# Prope rtie s
vis $ att rib1
...
vis $ att ribN = value
# Cons truc tor
funct ion __ cons tru ct (p1 ,...) {
stat emen ts
}
# Methods
vis func tion met hod1 (p1 ,...) {
stat emen ts
}
vis func tion met hodN (p1 ,...) {
stat emen ts
}
}
Every instance obj of this
class will have attributes
attrib1,. . . and methods
method1(), . . . accessible
as obj->attrib1 and
obj->method1(a1...)
__construct is the
constructor of the class and
will be called whenever
new identifier(a1,...)
is executed
vis is a declaration of the
visibility of each attribute
and method
COMP284 Scripting Languages Lecture 8 Slide L8 3
Classes Defining and Instantiating a Class
A Closer Look at Class Definitions
The pseudo-variable $this is available when a method is called from
within an object context and is a reference to the calling object
Inside method definitions, $this can be used to refer to the properties
and methods of the calling object
The object operator -> is used to access methods and properties of the
calling object
class Rect angle {
prot ected $ height ;
prot ected $ width ;
funct ion __ cons tru ct ( $height , $width ) {
$this - > wi dth = $wi dth ;
$this - > hei ght = $height ;
}
}
COMP284 Scripting Languages Lecture 8 Slide L8 4
Classes Visibility
Visibility
Properties and methods can be declared as
public accessible everywhere
private accessible only within the same class
protected accessible only within the class itself and
by inheriting and parent classes
For properties, a visibility
declaration is required
For methods, a visibility
declaration is optional
; by default, methods
are public
Accessing a private or
protected property /
method outside its visibility
is a fatal error
class Vis {
public $publi c = 1;
privat e $priv ate = 2;
prot ected $pro tect ed = 3;
prot ected funct ion proFc () {}
privat e funct ion priFc () {}
}
$v = new Vis ();
echo $v -> public ; # pri nts 1
echo $v -> privat e ; # Fatal Error
echo $v -> prot ecte d ; # Fatal Error
echo $v -> priFc (); # Fatal Error
echo $v -> proFc (); # Fatal Error
COMP284 Scripting Languages Lecture 8 Slide L8 5
Classes Class Constants
Constants
Classes can have their own constants and
constants can be declared to be public, private or protected
; by default, class constants are public
vis const iden tifi er = value ;
Accessing a private or protected constant outside its visibility
is a fatal error ; execution of the script stops
Class constants are allocated once per class,
and not for each class instance
Class constants are accessed using the scope resolution operator ::
class M yClass {
const SIZE = 10;
}
echo MyC lass :: SIZE ; # prints 10
$o = new MyC lass ();
echo $o :: SIZE ; # prints 10
COMP284 Scripting Languages Lecture 8 Slide L8 6
Classes Static Properties and Methods
Static Properties and Methods
Class properties or methods can be declared static
Static class properties and methods are accessed (via the class) using
the scope resolution operator ::
Static class properties cannot be accessed via an instantiated
class object, but static class methods can
Static class method have no access to $this
class E mploy ee {
static $ t ota lNumber = 0;
public $name ;
funct ion __ cons tru ct ( $name ) {
$this - > name = $name ;
Emplo yee :: $tot alN umbe r ++;
} }
$e1 = new E mploy ee (" Ada " );
$e2 = new E mploy ee (" Ben " );
echo Em ploye e :: $ t ota lNum ber # print s 2
COMP284 Scripting Languages Lecture 8 Slide L8 7
Classes Destructors
Destructors
A class can have a destructor method __destruct that will be called as
soon as there are no references to a particular object
class E mploy ee {
static $ t ota lNumber = 0;
public $name ;
funct ion __ cons tru ct ( $name ) {
$this - > name = $name ;
Emplo yee :: $tot alN umbe r ++;
}
funct ion __ dest ruct () {
Emplo yee :: $t otalNumber --;
}
}
$e1 = new E mploy ee (" Ada " );
$e2 = new E mploy ee (" Ben " );
echo Em ploye e :: $ t ota lNum ber # print s 2
$e1 = null ;
echo Em ploye e :: $ t ota lNum ber # print s 1
COMP284 Scripting Languages Lecture 8 Slide L8 8
Classes Inheritance
Inheritance
In a class definition it is possible to specify one parent class from which
a class inherits constants, properties and methods:
class ide ntif ier1 extends iden tif ier2 { ... }
The constructor of the parent class is not automatically called it must
be called explicitly from the child class
Inherited constants, properties and methods can be overridden by
redeclaring them with the same name defined in the parent class
The declaration final can be used to prevent a method from being
overriden
Using parent:: it is possible to access overridden methods or static
properties of the parent class
Using self:: it is possible to access static properties and methods of
the current class
COMP284 Scripting Languages Lecture 8 Slide L8 9
Classes Inheritance
Inheritance: Example
class Recta n gle {
pro tecte d $ heig ht ;
pro tecte d $ wid th ;
fu n ctio n _ _const r uct ( $height , $w idth ) {
$this - > he igh t = $heig ht ;
$this - > width = $ wi dth ;
}
fu n ctio n area () {
re turn $this -> w idt h * $this -> height ;
} }
class Squ are exten ds Rect a ngle {
fu n ctio n _ _const r uct ( $ si ze ) {
pa rent :: _ _const r uct ( $size , $ size );
} }
$rt1 = new Rect a ngle (3 ,4);
echo " \ $ rt1 area = " , $rt1 - > area () ,"\n " ;
$sq1 = new Square (5);
echo " \ $ sq1 area = " , $sq1 - > area () ,"\n " ;
$rt1 area = 12
$sq1 area = 25
COMP284 Scripting Languages Lecture 8 Slide L8 10
Classes Interfaces
Interfaces
Interfaces specify which methods a class must implement without
providing an implementation
Interfaces are defined in the same way as a class with the keyword
class replaced by interface
All methods in an interface must be declared public
A class can declare that it implements one ore more interfaces
using the implements keyword
inte rface Shape {
public fun ction area ();
}
class Rect angle impl emen ts Shape {
...
}
COMP284 Scripting Languages Lecture 8 Slide L8 11
Classes Introspection Functions
Introspection Functions
There are functions for inspecting objects and classes:
bool class_exists(string class)
returns TRUE iff a class class exists
class_exists('Rectangle') # returns TRUE
string get_class(object obj)
returns the name of the class to which an object belongs
get_class($sq1) # returns 'Square'
bool is_a(object obj, string class)
returns TRUE iff obj is an instance of class named class
is_a($sq1,'Rectangle') # returns TRUE
bool method_exists(object obj,string method)
returns TRUE iff obj has a method named method
method_exists($sq1,'area') # returns TRUE
COMP284 Scripting Languages Lecture 8 Slide L8 12
Classes Introspection Functions
Introspection Functions
There are functions for inspecting objects and classes:
bool property_exists(object obj,string property)
returns TRUE iff object has a property named property
property_exists($sq1,'size') # returns FALSE
array get_object_vars(object)
returns an array with the accessible non-static properties of object
mapped to their values
get_object_vars($e2)
# returns ["name" => "Ben"]
array get_class_methods(class)
returns an array of method names defined for class
get_class_methods('Square')
# returns ["__construct", "area"]
COMP284 Scripting Languages Lecture 8 Slide L8 13
Classes Introspection Functions
Revision
Read
Chapter 5: PHP Functions and Objects: PHP Objects
of R. Nixon: Learning PHP, MySQL, and JavaScript:
with jQuery, CSS & HTML5. O’Reilly, 2018.
Read
Language Reference: Classes and Objects
http://php.net/manual/en/language.oop5.php
of P. Cowburn (ed.): PHP Manual. The PHP Documentation
Group, 24 Dec 2019. http://uk.php.net/manual/en [accessed
25 Dec 2019]
COMP284 Scripting Languages Lecture 8 Slide L8 14