Web Programming: Object Oriented Programming and MVC
Web Programming: Object Oriented Programming and MVC
Action or Method
…give the function something
(arguments), it does something with
them, and then returns a result…
What is a class?
§ Conceptually, a class represents an object, with
associated methods (behaviours) and variables
(attributes)
Class Definition Example
Put the class definition into .php file, in this example in:
manusia.class.php
<?php
class manusia {
public $nama;
public function sayHello() {
echo 'Halo!';
}
}
?>
Class Defintion
§ Similar to defining a function..
§ The definition does not do anything by itself. It is
a blueprint, or description, of an object. To do
something, you need to use the class…
§ It means instantiating the class into object
Instantiating Class Into Object
§ Instantiate class into object without calling its
constructor function:
§ $objectVar = new ClassName;
Manusia
superclass
subclass
Dosen Mahasiswa
Inheritance Manusia
echo $susan->nama
. ' memakai baju warna '
. $susan->baju->warna;
Output:
Susan memakai baju warna merah
Abstract Class
§ It's a kind "father" that must be inherited to be used.
Classes that inherit differ from them only in the
abstract methods and can access the methods of the
parent class using the keyword parent.
§ Features:
§ can not be instantiated
§ methods can be abstract (not implemented)
§ methods may be not abstract (implemented)
§ a class can inherit from a single abstract class
Abstract Class
abstract class Binatang
{
abstract protected function bicara();
?>
Notes
§ PHP have "final" keyword to prevent sub-class
method overriding.
§ "final" keyword can be implemented on
properties, methods and classes
§ final class cannot be inherited
§ objects are destroyed in the end of PHP scripts.
§ Like regular variables, it is possible to explicitly
destroy an object using the unset() function.
A copy, or not a copy..
§ Entire objects can be passed as arguments to
functions, and can use all methods/variables
within the function.
§ Remember however… like functions the object is
COPIED when passed as an argument unless you
specify the argument as a reference variable
&$variable
Exercise
Binatang § Implements the class
+Nama
+Warna diagram in PHP
+Bicara()
+Makan()
+GarukGaruk()
§ Create a Unit Test script
to test all implemented
methods and attibutes
(properties).
Bebek Kucing
+Makan() +Makan()
0..*
+Bicara() +Bicara() Kutu
+Berenang() +Berlari() 1 +Melompat()
+TambahKutu()
Task
Task (2)
§ Ubah diagram class tersebut ke dalam kode program
PHP.
§ Penilaian diberikan pada keakuratan dan kesesuaian kode
program dengan diagram class