PHP - What Is OOP?
PHP - What Is OOP?
NOTE: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of
code. You should extract out the codes that are common for the application, and place them at
a single place and reuse them instead of repeating it.
When the individual objects are created, they inherit all the properties and behaviors from the
class, but each object will have different values for the properties.
Define a Class
A class is defined by using the class keyword, followed by the name of the class and a pair of
curly braces ({}). All its properties and methods go inside the braces:
Syntax
<?php
class Fruit {
// code goes here...
}
?>
Lecture 21 Web Systems and Technologies
The special form class, followed by the name of the class that you want to define.
Variable declarations start with the special form var, which is followed by a
conventional $ variable name; they may also have an initial assignment to a
constant value.
Function definitions look much like standalone PHP functions but are local to the
class and will be used to set and access object data.
Note: In a class, variables are called properties and functions are called methods!
Here is an example which defines a class of Fruit type −
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
Lecture 21 Web Systems and Technologies
Once you defined your class, then you can create as many objects as you like of that class
type. Following is an example of how to create object using new operator.
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
In the example below, we add two more methods to class Fruit, for setting
and getting the $color property:
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
Lecture 21 Web Systems and Technologies
function get_name() {
return $this->name;
}
function set_color($color) {
$this->color = $color;
}
function get_color() {
return $this->color;
}
}
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
?>
So, where can we change the value of the $name property? There are
two ways:
1. Inside the class (by adding a set_name() method and use $this):
Example
<?php
class Fruit {
public $name;
function set_name($name) {
$this->name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");
?>
Lecture 21 Web Systems and Technologies
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";
?>