05 - OOP in PHP

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Vietnam and Japan Joint

ICT HRD Program

Object--Oriented Programming (OOP)


Object
Object: Instance (occurrance) of a class
Object:
Classes/Objects
Cl
/Obj t encapsulates
l t
th i d
their
data
t
(called attributes
attributes)) and behaviour (called
methods))
methods
Inheritance
Inheritance:: Defin
Define
e a new class by
saying that it's like an existing class, but
with certain new or changed attributes
and methods.

ICT 5 Web Development

Chapter 5. OOP in PHP


Nguyen Thi Thu Trang

The old class


class:: superclass
superclass//parent
parent//base class
The
The new class:
class: subclass
subclass/child/
/child/derived
derived class

[email protected]
trangntt

PHP 5

Content

Singleingle-inheritance

1. Creating an Object
2. Accessing attributes and methods
3. Building
Building a class
4. Introspection

Access
ccess--restricted
Overloadable
Object

~ passpass-byby-reference

1. Creating an Object

Content
1. Creating an Object
2. Accessing attributes and methods
3. Building
Building a class
4. Introspection

Syntax:
$object = new Class
Class([agrs])
([agrs]);
;

E.g.:
$obj1= new User();
User();
$obj2 = new User('Fred', "abc123"); //args
$obj3 = new User'; // does not work
$class = User';
User ; $obj4
$obj4= new $class; //ok
User
+ name
- password
- lastLogin
+ getLastLogin()
+ setPassword(pass)

2. Accessing Attributes and


Methods

Content
1. Creating an Object
2. Accessing attributes and methods
3. Building
Building a class
4. Introspection

Syntax: Using ->


$object$object->attribute_
attribute name
attribute_name
$object
$object->method
method_
_name
name([
([arg,
arg, ... ])
])

E.g.
// attribute access
$obj1$obj1
->name = Micheal";
print("User name is " . $obj1$obj1->name);
$obj1$obj1
->getLastLogin( ); // method call
// method call with args
$obj1$obj1
->setPassword("Test4");

Rules for PHP


Identifiers

3.1. Syntax to declare a Class


class Class
lassN
Name [extends Base
aseC
Class
lass]{
]{
[[var
var]
] access $attribute [ = value ]; ... ]
[access function method
method_name
_name (args
args)
) {
// code
} ...
]
}

access can be: public


public,, protected or private (default is
public).
ClassNames,
ClassName
s, atributes, methods are casecase-sensitive and
conform the rules for PHP identifiers
attributes or methods can be declared as static or const

Must include:

ASCII letter
(a--zA
(a
zA--Z)
Digits (0(0-9)
_
ASCII character
between 0x7F
(DEL) and
0xFF

Do not start
by a digit

Example Define User class

10

3.2. Constructors and Destructors

User

//define class for tracking users


+ name
- password
class User {
- lastLogin
public $name;
+ getLastLogin()
private $password, $lastLogin;
public function __
__construct($name, $password) {
$this$this
->name = $name;
A special variable
$this$this
->password = $password;
for the particular instance
$this$this
->lastLogin = time();
of the class
}
function getLastLogin() {
return(date("M d Y", $this$this->lastLogin));
}
}
11

Constructor
__construct([agrs])
construct([agrs])
executed immediately upon creating an object
from that class

Destructor
__destruct()
destroying
ying the object
calls when destro

2 special namespaces:
selft: refers to the current class
parent: refers to the immediate ancestor
Call parents constructor: parent::__construct
12

class BaseClass{
protected $name = "BaseClass";
function __construct(){
print("In " . $this
$this->name . " constructor<br>");
}
function __destruct(){
print("Destroying
p
(
y g " . $
$this->name . "<br>");
$this);
}
}
class SubClass extends BaseClass {
function __construct(){
$this$this
->name = "SubClass";
parent::__construct();
}
function __destruct(){
parent::__destruct();
}
}

Example

$obj1 = new SubClass();


$obj2 = new BaseClass();

3.3. Static & constant class members

Static member
Not relate
relate/belong
/belong to an any particular object of the
class, but to the class itself.
itself.
Cannot use $this to access static members but can use
with self namespace or ClassName.

E.g.
count

is a static attribute of Counter class


or Counter::$count

self::$count

Constant member
value cannot be changed
can be accessed directly through the class or within
object methods using the self namespace.

13

class Counter {
private static $count = 0;
const VERSION = 2.0;
function __construct(){ self::$count++; }
function __destruct(){ self::$count-self::$count--;
; }
static function getCount() {
return self::$count;
}
}
$c1 = new Counter();
print($c1print($c1
->getCount() . "<br>
"<br>\
\n");
$c2 = new Counter();
print(Counter::getCount() . "<br>\
"<br>\n");

14

Example

3.4. Cloning Object


$a = new SomeClass();
$b = $
$a;
// $a and $b point to the same
underlying instance of SomeClass

Changing $a attributes value also make


$b attributes changing
Create a replica of an object so that
changes to the replica are not reflected in
the original object? CLONING

$c2 = NULL;
print($c1print($c1
->getCount() . "<br>
"<br>\
\n");
print("Version used: ".Counter::VERSION."<br>\
".Counter::VERSION."<br>\n");
15

16

Example Cloning

class ObjectTracker {
private static $nextSerial = 0;
private $id, $name;
function __construct($name) {
$this$this
->name = $name;
thisthis
->id = ++self::$nextSerial;
}
function __clone(){
$this$this
->name = "Clone of $th
$this
is->name";
$this$this
->id = ++self::$nextSerial;
}
function getId() { return($thisreturn($this->id); }
function getName() { return($thisreturn($this->name); }
function setName($name) { $this$this->name = $name; }
}
$ot = new ObjectTracker("Zeev's Object");
$ot2 = clone $ot; $ot2$ot2->setName("Another object");
print($otprint($ot
->getId() . " " . $ot
$ot->getName() . "<br>");
print($ot2print($ot2
->getId() . " " . $ot2
$ot2->getName() . "<br>");

3.4. Object Cloning

Special method in every class: __clone()


Every object has a default implementation for
__clone()
Accepts no arguments

Call cloning:
$copy_of_object = clone $object;
E.g.
E
$a = new SomeClass();
$b = clone $a;

17

18

3.5. UserUser-level overloading

3.5.1. Attribute overloading

Overloading in PHP provides means


dynamic "create"
create attributes and methods
methods.
The overloading methods are invoked
when interacting with attributes or
methods that have not been declared or
are not visible in the current scope.
All overloading methods must be defined
as public
public..

void __set (string $name , mixed $value)

mixed __get (string $name)

bool __isset (string $name)

is run when writing data to inaccessible attributes


is utilized for reading data from inaccessible attributes
is triggered by calling isset() or empty() on inaccessible
attributes

void __unset
unset (string $name)
is invoked when unset() is used on inaccessible
attributes

19

Note: The return value of __set() is ignored because of the way PHP
processes the assignment operator. Similarly, __get() is never
called when chaining assignments together like this:
$a = $obj$obj->b = 8;
20

class PropertyTest {
private $data = array();
Example - Attribute overloading
public $declared = 1;
private $hidden = 2;
public function __set($name, $value) {
echo "Setting '$name' to '$value'<br>";
thisthis
->data[$name] = $value;
}
public function __get($name)
get($name) {
echo "Getting '$name'<br>";
if (array_key_exists($name, $this$this->data)) {
return $this$this->data[$name];
}
$obj = new PropertyTest;
}
public function __isset($name) {
$obj$obj
->a = 1;
echo "Is '$name' set?<br>";
$obj->a."<br>";
return isset($thisisset($this->data[$name]); echo $obj}
var_dump(isset($objvar_dump(isset($obj
->a));
public function __unset($name) {
unset($objunset($obj
->a);
echo "Unsetting '$name'<br>";
var_dump(isset($objvar_dump(isset($obj
->a));
unset($thisunset($this
->data[$name]);
echo "<br>";
}
public function getHidden() {
echo $obj$obj->declared."<br>";
return $this$this->hidden;
echo $obj$obj->getHidden()."<br>";
}
echo $obj$obj->hidden."<br>";
}

3.5.2. Method overloading

mixed __call (string $name, array


$arguments)

is triggered when invoking inaccessible


methods in an object context
mixed __callStatic (string $name,
array $arguments)
is
i ttriggered
i
d when
h
invoking
i
ki
inaccessible
i
ibl
methods in a static context.

22

Example
Method Overloading

3.6. Autoloading class

class MethodTest {
public function __call($name, $arguments) {
// Note: value of $name is case sensitive.
echo "Calling object method '$name' "
. implode(', ', $arguments). <br>";
}

Using a class you havent defined, PHP


generates a fatal error
Can use include statement
Can use a global function __autoload()

public static function __callStatic($name, $arguments) {


// Note: value of $name is case sensitive.
echo "Calling static method '$name' "
. implode(', ', $arguments). <br>";
}
}
$obj = new MethodTest;
$obj$obj
->runTest('in object context');

single parameter: the name of the class


automatically called when you attempt to use
a class PHP does not recognize

MethodTest::runTest('in static context');

23

24

Example - Autoloading class

3.7. Namespace

//define autoload function


function __autoload($class)
autoload($class) {
include("class_".ucfirst($class).".php");
}
//use a class that must be autoloaded
$u = new User;
$u$u
$
->name = "Leon";
;
$u$u
->printName();

~folder, ~package
Organize
O
i variables,
i bl
ffunctions
ti
and
d classes
l
Avoid confliction in naming variables,
functions and classes
The namespace statement gives a name
to a block of code
From outside the block, scripts must refer
to the parts inside with the name of the
namespace using the :: operator

25

26

Example Namespace

3.7. Namespace (2)


You cannot create a hierarchy of
namespaces
namespaces name includes colons as
long as they are not the first character,
the last character or next to another colon
use colons to divide the names of your
namespaces into logical partitions like
parent--child relationships to anyone who
parent
reads your code
E.g. namespace hedspi:is1 { ... }

27

namespace core_php:utility {
class TextEngine {
public function uppercase($text) {
return(strtoupper($text));
}
import * from myNamespace
}
function uppercase($text) {
$e = new TextEngine;
return($ereturn($e
->uppercase($text));
}
}
$e = new core_php:utility::textEngine;
print($eprint($e
->uppercase("from object") . "<br>");
print(core_php:utility::uppercase("from function")
."<br>");
import class TextEngine from core_php:utility;
$e2 = new textEngine;
28

3.8. Abstract methods and


abstract classes

abstract class Shape {


abstract function getArea();
}
abstract class Polygon extends Shape {
abstract function g
getNumberOfSides();
();
}
class Triangle extends Polygon {
public $base; public $height;
public function getArea() {
return(($thisreturn(($this
->base * $this
$this->height)/2);
}
public function getNumberOfSides() {
return(3);
}
}

Single

inheritance
Abstract methods, abstract classes,
interface (implements) like Java
You cannot instantiate an
an abstract
class,, but you can extend it or use it
class
in an instanceof expression

29

30

$myCollection = array();

class Rectangle extends Polygon {


public $width; public $height;
public function getArea() {
return($thisreturn($this
->width * $this
$this->height);
}
public function getNumberOfSides() {
return(4);
}
}
class Circle extends Shape {
public $radius;
public function getArea() {
return(pi() * $this$this->radius * $this
$this->radius);
}
}
class Color {
public $name;
}

$r = new Rectangle; $r$r->width = 5; $r


$r->height = 7;
$myCollection[] = $r; unset($r);
$t = new Triangle; $t$t->base = 4; $t
$t->height = 5;
$myCollection[] = $t; unset($t);
$c = new Circle; $c$c->radius = 3;
$myCollection[] = $c; unset($c);
$c = new Color; $c$c->name = "blue";
$myCollection[] = $c; unset($c);

31

foreach($myCollection as $s) {
if($s instanceof Shape) {
print("Area: " . $s$s->getArea() . "<br>
"<br>\
\n");
}
if($s
($ instanceof Polygon)
yg ) {
print("Sides: " . $s$s->getNumberOfSides() . "<br>
"<br>\
\n");
}
if($s instanceof Color) {
print("Color: $s$s->name<br>
>name<br>\
\n");
}
print("<br>\
print("<br>
\n");
32
}

Content

4. Introspection

1. Creating an Object
2. Accessing attributes and methods
3. Building
Building a class
4. Introspection

Ability of a program to examine an


object's
object
s characteristics
characteristics, such as its name
name,
parent class (if any), attributes, and
methods..
methods
Discover which methods or attributes are
defined when you write your code at
runtime which makes it possible for you
runtime,
to write generic debuggers, serializers,
profilers, etc

33

4.1. Examining Classes

class_exists(c
class_exists(
class
lassn
name)
determine whether a class exists

get_declared_cl
get_declared_c
lasses()

get_class_methods(classname
get_class_methods(
classname)
)

get_class_vars
_
_
(classname)
(classname
)

get_parent_class(classname
get_parent_class(
classname)
)

returns an array of defined classes


Return an array of methods that exist in a class
Return an array of attributes that exist in a class
Return name of the parent class
Return FALSE if there is no parent class
35

34

function display_classes ( ) {
$classes = get_declared_classes( );
foreach($classes as $class) {
echo "Showing information about $class<br />";
echo "$class methods:<br />";
$methods = get_class_methods($class);
if(!count($methods)) {
echo "<i>None</i><br
<i>None</i><br />";
/> ;
} else { foreach($methods as $method) {
echo "<b>$method</b>( )<br />";
}
}
echo "$class attributes:<br />";
$attributes = get_class_vars($class);
if(!count($attributes)) { echo "<i>None</i><br />; }
else {
foreach(array_keys($attributes) as $attribute) {
echo "<b>\
"<b>\$$attribute</b><br />";
}
}
echo "<b
"<br />";
}
}
36

4.2. Examining an Object

is_object(object
is_object(
object)
)

get_class(object)

method_exists(object,
method_exists(
object, method
method)
)

get_object
get_
_object_vars(
_vars( object
_
object)
)

get_parent_class(object
get_parent_class(
object)
)

Question?

Check if a variable is an object or not


Return the class of the object
Check if a method exists in object or not
Return an array of attributes that exist in a class
Return the name of the parent class
Return FALSE if there is no parent class
37

38

10

You might also like