- Object-oriented programming (OOP) refers to the creation of reusable software objects/classes that can be efficiently developed and incorporated into multiple programs. An OOP program consists of interacting objects that solve a task.
- Classes define objects of the same type through data members (properties) and methods. Objects are instances of classes that can inherit properties and behaviors from parent classes.
- OOP principles like encapsulation, inheritance, and polymorphism help manage complexity through modularization and reuse when building large PHP programs.
2. Why use classes and objects?
• PHP is a primarily procedural language
• small programs are easily written without
adding any classes or objects
• larger programs, however, become cluttered
with so many disorganized functions
• grouping related data and behavior into
objects helps manage size and complexity
CS380 2
3. OOP with PHP
why OOP in PHP
Common OOP approach advantages
• Modularity
• Less code
• Reusability
• Robustness
• Handling large projects, easy to maintain
• Classes usually reflect database schema
• PHP is not inherently OOP language!
4. OOP with PHP
why OOP in PHP – examples
• Online shops
• Banking systems
• News services
• Editors' systems
• Home pages
• => use OOP to separate the functionality
from layout
6. • Object-oriented programming (OOP) refers to the
creation of reusable software object-types / classes that
can be efficiently developed and easily incorporated into
multiple programs.
• In OOP an object represents an entity in the real world
(a student, a desk, a button, a file, a text input area, a
loan, a web page, a shopping cart).
• An OOP program = a collection of objects that interact to
solve a task / problem.
Object-Oriented Programming
6
7. • Classes are constructs that define objects of the same type.
A class is a template or blueprint that defines what an
object’s data and methods will be.
Objects of a class have:
– Same operations, behaving the same way
– Same attributes representing the same features, but
values of those attributes (= state) can vary from object to
object
• An object is an instance of a class.
(terms objects and instances are used interchangeably)
• Any number of instances of a class can be created.
Object-Oriented Programming
7
8. 8
Example: A “Rabbit” object
• You could (in a game, for example) create an
object representing a rabbit
• It would have data:
– How hungry it is
– How frightened it is
– Where it is
• And methods:
– eat, hide, run, dig
9. Constructing and using objects
9
# construct an object
$name = new ClassName(parameters);
# access an object's field (if the field is public)
$name->fieldName
# call an object's method
$name->methodName(parameters);
PHP
• the above code unzips a file
• test whether a class is installed with class_exists
CS380
$zip = new ZipArchive();
$zip->open("moviefiles.zip");
$zip->extractTo("images/");
$zip->close(); PHP
10. PHP Class
• A class can contain it’s own constants, variables (called
“Properties”) and functions (calles “methods”).
11. Class declaration syntax
11
class ClassName {
# fields - data inside each object
public $name; # public field
private $name; # private field
# constructor - initializes each object's
state
public function __construct(parameters) {
statement(s);
}
# method - behavior of each object
public function name(parameters) {
statements;
}
} PHP
• inside a constructor or method, refer to the current object as
$this
12. Class example
12
<?php
class Point {
public $x;
public $y;
# equivalent of a Java constructor
public function __construct($x, $y) {
$this->x = $x;
$this->y = $y;
}
public function distance($p) {
$dx = $this->x - $p->x;
$dy = $this->y - $p->y;
return sqrt($dx * $dx + $dy * $dy);
}
# equivalent of Java's toString method
public function __toString() {
return "(" . $this->x . ", " . $this->y .
")";
}
} ?> PHP
13. 13
Example of a class
class Employee {
// Fields
private String name; //Can get but not change
private double salary; // Cannot get or set
// Constructor
Employee(String n, double s) {
name = n; salary = s;
}
// Methods
void pay () {
System.out.println("Pay to the order of " +
name + " $" + salary);
}
public String getName() { return name; } // getter
}
14. • Destructor = opposite of constructor
– Allows some functionality that will be automatically
executed just before an object is destroyed
An object is removed when there is no reference
variable/handle left to it
Usually during the "script shutdown phase", which is typically
right before the execution of the PHP script finishes
– A default destructor provided by the compiler only if a
destructor function is not explicitly declared in the class
Creating Classes in PHP
14
15. Constructors
• All objects can have a special built-in method called a
'constructor'. Constructors allow you to initialize your object's
properties (translation: give your properties values,) when
you instantiate (create) an object.
16. Destructor
• <?php
class MyDestructableClass {
function __construct() {
print "In constructorn";
$this->name = "MyDestructableClass";
}
function __destruct() {
print "Destroying " . $this->name . "n";
}
}
$obj = new MyDestructableClass();
?>
17. Once a class has been created, any number of object instances of
that class can be created.
$dogRobot = new Robot();
To invoke methods:
object->method()
Instantiating Classes
17
e.g.
<?php
....
$dogRobot = new Robot();
$dogRobot ->crawlWeb();
$dogRobot -> play();
echo $dogRobot ->talk();
... ?>
18. • From operations within the class, class’s data /
methods can be accessed / called by using:
– $this = a variable that refers to the current instance of the class, and can
be used only in the definition of the class.
– The pointer operator -> (similar to Java’s object member access operator “.” )
– class Test {
public $attribute;
function f ($val) {
$this -> attribute = $val; // $this is mandatory!
} // if omitted, $attribute is treated
} // as a local var in the function
Using Data/Method Members
18
19. • From outside the class, accessible (as determined by access
modifiers) data and methods are accessed through a variable
holding an instance of the class, by using the same pointer operator.
class Test {
public $attribute;
}
$t = new Test();
$t->attribute = “value”;
echo $t->attribute;
Using Data/Method Members
19
20. Visibility of a method or data member:
Public
Protected
Private
By default, without the access specifies, class members
are defined public.
Defining and Using Variables, Constants
and Functions
20
21. • Class members declared public can be
accessed everywhere.
• Members declared protected can be accessed
only within the class itself and by inherited
classes
• Members declared as private may only be
accessed by the class that defines the
member.
22. Encapsulation
• Data members are normally set inaccessible
from outside the class (as well as certain types
of methods) protecting them from the rest of
the script and other classes.
• This protection of class members is known as
encapsulation.
23. Encapsulation
• <?php
class App {
private static $_user;
public function User( ) {
if( $this->_user == null )
{
$this->_user = new User();
}
return $this->_user;
} }
?>
25. Inheritance in PHP
• Inheritance is a concept in object oriented programming. With
the help of inheritance we can get all property and method of
one class in another class. This is principle to take re-
fusibility on upper level. Inheritance in php is introduced
from php5 version.
26. Inheritance
• New classes can be defined very similar to existing ones. All
we need to do is specify the differences between the new
class and the existing one.
• Data members and methods which are not defined as being
private to a class are automatically accessible by the new
class.
• This is known as inheritance and is an extremely powerful
and useful programming tool.
27. Inheritance
• class Animal {
public $name;
public function Greet()
{
return "Hello, I'm some sort of animal and my
name is " . $this->name; }
}
28. Inheritance
class Dog extends Animal {
public function Greet()
{ return "Hello, I'm a dog and my name is " .
$this->name; }
}
30. Overriding methods
• Sometimes (when using inheritance,) you may need to change
how a method works from the base class.
• For example, let's say set_name() method in the 'employee'
class, had to do something different than what it does in the
'person' class.
• You 'override' the 'person' classes version of set_name(), by
declaring the same method in 'employee'.
32. OOP with PHP
Overloading in PHP
<?php
class ShoppingCart{
function ShoppingCart(){
$to_call="ShoppingCart".func_num_args();
$args = func_get_args(); // return an array of arguments
$args = implode(':',$args);
$args = str_replace(“:”, “,”, $args);
$run = “$this->$to_call ($args);”; // variable variable
eval ($run);
}
function ShoppingCart1($x=”2”) { code1();}
function ShoppingCart2($x=”2”,$y=”3”) { code2();}
}
?>
33. OOP with PHP
Polymorphism
• All class member functions are virtual by
the definition
class A {
function draw() { echo "1"; } // not needed
function boo() { $this->draw(); }
}
class B extends A {
function draw() { echo "drawing B"; }
}
$b = new B();
$b->boo(); // outputs “drawing B”
34. what is abstract class in php?
• An abstract class is a class that contains at least one abstract
method, which is a method without any actual code in it, just
the name and the parameters, and that has been marked as
"abstract".
• The purpose of this is to provide a kind of template to inherit
from and to force the inheriting class to implement the
abstract methods.
• An abstract class thus is something between a regular class
and a pure interface. Also interfaces are a special case of
abstract classes where ALL methods are abstract.
36. PHP Interfaces
• interfaces exist not as a base on which classes can extend but
as a map of required functions.
• The entire point of interfaces is to give you the flexibility to
have your class be forced to implement multiple interfaces,
but still not allow multiple inheritance. The issues with
inheriting from multiple classes
38. Differences between abstract class and
interface in PHP
• In abstract classes this is not necessary that every method
should be abstract. But in interface every method is abstract.
• Multiple and multilevel both type of inheritance is possible in
interface. But single and multilevel inheritance is possible in
abstract classes.
• Method of php interface must be public only. Method in
abstract class in php could be public or protected both.
• In abstract class you can define as well as declare methods.
But in interface you can only defined your methods.
39. Object example: Fetch file from web
39
# create an HTTP request to fetch student.php
$req = new HttpRequest("student.php",
HttpRequest::METH_GET);
$params = array("first_name" => $fname, "last_name"
=> $lname);
$req->addPostFields($params);
# send request and examine result
$req->send();
$http_result_code = $req->getResponseCode(); # 200
means OK
print "$http_result_coden";
print $req->getResponseBody();
PHP
• PHP's HttpRequest object can fetch a document from the
web
CS380
40. OOP with PHP
Generic function for setting the member
variables
function Set ($varname, $value) {
$this->$varname = $value;
}
$instance->Set ('size','5');
41. OOP with PHP
Serializing the objects
• Partially overcomes the need for a persistent
object
• !!Saves only data members, not methods!
(PHP4 is exception)
<?php
$myCart = new ShoppingCart();
$stream1 = serialize($myCart); // and store to file or db
...
... // retreive from file/db after a year..
$myLaterCart = unserialize($stream1);
?>
• Not recommended to use!
Editor's Notes
If ref var is assigned null -> destructor called if no other ref var left to that object!