Tip: The "Don't Repeat Yourself" (DRY) Principle Is About Reducing The Repetition of Code. You
Tip: The "Don't Repeat Yourself" (DRY) Principle Is About Reducing The Repetition of Code. You
Tip: 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.
Classes and objects are the two main aspects of object-oriented programming.
Look at the following illustration to see the difference between class and objects:
class
Fruit
objects
Apple
Banana
Mango
Another example:
class
Car
objects
Volvo
Audi
Toyota
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.
OOP Case
Let's assume we have a class named Fruit. A Fruit can have properties like
name, color, weight, etc. We can define variables like $name, $color, and
$weight to hold the values of these properties.
When the individual objects (apple, banana, etc.) 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...
}
?>
Below we declare a class named Fruit consisting of two properties ($name and
$color) and two methods set_name() and get_name() for setting and getting
the $name property:
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
Try it Yourself »
Note: In a class, variables are called properties and functions are called
methods!
Define Objects
Classes are nothing without objects! We can create multiple objects from a
class. Each object has all the properties and methods defined in the class, but
they will have different property values.
In the example below, $apple and $banana are instances of the class Fruit:
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
Try it Yourself »
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;
}
function get_name() {
return $this->name;
}
function set_color($color) {
$this->color = $color;
}
function get_color() {
return $this->color;
}
}
$apple = new Fruit();
$apple->set_name('Apple');
$apple->set_color('Red');
echo "Name: " . $apple->get_name();
echo "<br>";
echo "Color: " . $apple->get_color();
?>
Try it Yourself »
Example
<?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");
?>
Try it Yourself »
Example
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";
?>
Try it Yourself »
PHP - instanceof
You can use the instanceof keyword to check if an object belongs to a specific
class:
Example
<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit);
?>
PHP OOP - Constructor
Notice that the construct function starts with two underscores (__)!
We see in the example below, that using a constructor saves us from calling the
set_name() method which reduces the amount of code:
Example
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit("Apple");
echo $apple->get_name();
?>
Try it Yourself »
Another example:
Example
<?php
class Fruit {
public $name;
public $color;
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function get_name() {
return $this->name;
}
function get_color() {
return $this->color;
}
}
$apple = new Fruit("Apple", "red");
echo $apple->get_name();
echo "<br>";
echo $apple->get_color();
?>
PHP OOP - Destructor
Notice that the destruct function starts with two underscores (__)!
Example
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}
$apple = new Fruit("Apple");
?>
Try it Yourself »
Another example:
Example
<?php
class Fruit {
public $name;
public $color;
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function __destruct() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
$apple = new Fruit("Apple", "red");
?>
PHP OOP - Access Modifiers
In the following example we have added three different access modifiers to the
three properties. Here, if you try to set the name property it will work fine
(because the name property is public). However, if you try to set the color or
weight property it will result in a fatal error (because the color and weight
property are protected and private):
Example
<?php
class Fruit {
public $name;
protected $color;
private $weight;
}
$mango = new Fruit();
$mango->name = 'Mango'; // OK
$mango->color = 'Yellow'; // ERROR
$mango->weight = '300'; // ERROR
?>
Try it Yourself »
In the next example we have added access modifiers to two methods. Here, if
you try to call the set_color() or the set_weight() function it will result in a fatal
error (because the two functions are considered protected and private), even if
all the properties are public:
Example
<?php
class Fruit {
public $name;
public $color;
public $weight;
$mango = new Fruit();
$mango->set_name('Mango'); // OK
$mango->set_color('Yellow'); // ERROR
$mango->set_weight('300'); // ERROR
?>
PHP OOP - Inheritance
PHP - What is Inheritance?
Inheritance in OOP = When a class derives from another class.
The child class will inherit all the public and protected properties and methods
from the parent class. In addition, it can have its own properties and methods.
Example
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
Example Explained
The Strawberry class is inherited from the Fruit class.
This means that the Strawberry class can use the public $name and $color
properties as well as the public __construct() and intro() methods from the Fruit
class because of inheritance.
Example
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
protected function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
Try it Yourself »
Example
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
protected function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
Try it Yourself »
In the example above we see that all works fine! It is because we call
the protected method (intro()) from inside the derived class.
Look at the example below. The __construct() and intro() methods in the child
class (Strawberry) will override the __construct() and intro() methods in the
parent class (Fruit):
Example
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
Try it Yourself »
Example
<?php
final class Fruit {
// some code
}
Try it Yourself »
Class constants can be useful if you need to define some constant data within a
class.
We can access a constant from outside the class by using the class name
followed by the scope resolution operator (::) followed by the constant name,
like here:
Example
<?php
class Goodbye {
const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";
}
echo Goodbye::LEAVING_MESSAGE;
?>
Try it Yourself »
Or, we can access a constant from inside the class by using the self keyword
followed by the scope resolution operator (::) followed by the constant name,
like here:
Example
<?php
class Goodbye {
const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";
public function byebye() {
echo self::LEAVING_MESSAGE;
}
}
$goodbye = new Goodbye();
$goodbye->byebye();
?>
PHP OOP - Abstract Classes
PHP - What are Abstract Classes and
Methods?
Abstract classes and methods are when the parent class has a named method,
but need its child class(es) to fill out the tasks.
Syntax
<?php
abstract class ParentClass {
abstract public function someMethod1();
abstract public function someMethod2($name, $color);
abstract public function someMethod3() : string;
}
?>
When inheriting from an abstract class, the child class method must be defined
with the same name, and the same or a less restricted access modifier. So, if
the abstract method is defined as protected, the child class method must be
defined as either protected or public, but not private. Also, the type and number
of required arguments must be the same. However, the child classes may have
optional arguments in addition.
So, when a child class is inherited from an abstract class, we have the following
rules:
The child class method must be defined with the same name and it
redeclares the parent abstract method
The child class method must be defined with the same or a less restricted
access modifier
The number of required arguments must be the same. However, the child
class may have optional arguments in addition
Let's look at an example:
Example
<?php
// Parent class
abstract class Car {
public $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function intro() : string;
}
// Child classes
class Audi extends Car {
public function intro() : string {
return "Choose German quality! I'm an $this->name!";
}
}
class Volvo extends Car {
public function intro() : string {
return "Proud to be Swedish! I'm a $this->name!";
}
}
class Citroen extends Car {
public function intro() : string {
return "French extravagance! I'm a $this->name!";
}
}
$volvo = new volvo("Volvo");
echo $volvo->intro();
echo "<br>";
$citroen = new citroen("Citroen");
echo $citroen->intro();
?>
Try it Yourself »
PHP OOP - Traits
PHP - What are Traits?
PHP only supports single inheritance: a child class can inherit only from one
single parent.
So, what if a class needs to inherit multiple behaviors? OOP traits solve this
problem.
Traits are used to declare methods that can be used in multiple classes. Traits
can have methods and abstract methods that can be used in multiple classes,
and the methods can have any access modifier (public, private, or protected).
Syntax
<?php
trait TraitName {
// some code...
}
?>
Syntax
<?php
class MyClass {
use TraitName;
}
?>
class Welcome {
use message1;
}
$obj = new Welcome();
$obj->msg1();
?>
Try it Yourself »
Example Explained
Here, we declare one trait: message1. Then, we create a class: Welcome. The
class uses the trait, and all the methods in the trait will be available in the class.
If other classes need to use the msg1() function, simply use the message1 trait
in those classes. This reduces code duplication, because there is no need to
redeclare the same method over and over again.
Example
<?php
trait message1 {
public function msg1() {
echo "OOP is fun! ";
}
}
trait message2 {
public function msg2() {
echo "OOP reduces code duplication!";
}
}
class Welcome {
use message1;
}
class Welcome2 {
use message1, message2;
}
$obj = new Welcome();
$obj->msg1();
echo "<br>";
$obj2 = new Welcome2();
$obj2->msg1();
$obj2->msg2();
?>
Try it Yourself »
Example Explained
Here, we declare two traits: message1 and message2. Then, we create two
classes: Welcome and Welcome2. The first class (Welcome) uses the message1
trait, and the second class (Welcome2) uses both message1 and message2
traits (multiple traits are separated by comma).
PHP OOP - Static Methods
PHP - Static Methods
Static methods can be called directly - without creating an instance of a class.
Syntax
<?php
class ClassName {
public static function staticMethod() {
echo "Hello World!";
}
}
?>
To access a static method use the class name, double colon (::), and the
method name:
Syntax
ClassName::staticMethod();
Example
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
}
Example Explained
Here, we declare a static method: welcome(). Then, we call the static method
by using the class name, double colon (::), and the method name (without
creating a class first).
Example
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
public function __construct() {
self::welcome();
}
}
new greeting();
?>
Try it Yourself »
Static methods can also be called from methods in other classes. To do this, the
static method should be public:
Example
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
}
class SomeOtherClass {
public function message() {
greeting::welcome();
}
}
?>
Try it Yourself »
To call a static method from a child class, use the parent keyword inside the
child class. Here, the static method can be public or protected.
Example
<?php
class domain {
protected static function getWebsiteName() {
return "W3Schools.com";
}
}
class domainW3 extends domain {
public $websiteName;
public function __construct() {
$this->websiteName = parent::getWebsiteName();
}
}
$domainW3 = new domainW3;
echo $domainW3 -> websiteName;
?>
Try it Yourself »
PHP OOP - Static Properties
PHP - Static Properties
Static properties can be called directly - without creating an instance of a class.
Syntax
<?php
class ClassName {
public static $staticProp = "W3Schools";
}
?>
To access a static property use the class name, double colon (::), and the
property name:
Syntax
ClassName::staticProp;
Example
<?php
class pi {
public static $value = 3.14159;
}
Try it Yourself »
Example Explained
Here, we declare a static property: $value. Then, we echo the value of the static
property by using the class name, double colon (::), and the property name
(without creating a class first).
Example
<?php
class pi {
public static $value=3.14159;
public function staticValue() {
return self::$value;
}
}
$pi = new pi();
echo $pi->staticValue();
?>
Try it Yourself »
To call a static property from a child class, use the parent keyword inside the
child class:
Example
<?php
class pi {
public static $value=3.14159;
}
class x extends pi {
public function xStatic() {
return parent::$value;
}
}
PHP Namespaces
Namespaces are qualifiers that solve two different problems:
1. They allow for better organization by grouping classes that work together
to perform a task
2. They allow the same name to be used for more than one class
For example, you may have a set of classes which describe an HTML table, such
as Table, Row and Cell while also having another set of classes to describe
furniture, such as Table, Chair and Bed. Namespaces can be used to organize
the classes into two different groups while also preventing the two classes Table
and Table from being mixed up.
Declaring a Namespace
Namespaces are declared at the beginning of a file using the namespace keyword:
Syntax
Declare a namespace called Html:
namespace Html;
<?php
echo "Hello World!";
namespace Html;
...
?>
Example
Create a Table class in the Html namespace:
<?php
namespace Html;
class Table {
public $title = "";
public $numRows = 0;
public function message() {
echo "<p>Table '{$this->title}' has {$this->numRows} rows.</p>";
}
}
$table = new Table();
$table->title = "My table";
$table->numRows = 5;
?>
<!DOCTYPE html>
<html>
<body>
<?php
$table->message();
?>
</body>
</html>
Try it Yourself »
Syntax
Declare a namespace called Html inside a namespace called Code:
namespace Code\Html;
Using Namespaces
Any code that follows a namespace declaration is operating inside the namespace,
so classes that belong to the namespace can be instantiated without any
qualifiers. To access classes from outside a namespace, the class needs to have
the namespace attached to it.
Example
Use classes from the Html namespace:
$table = new Html\Table()
$row = new Html\Row();
Try it Yourself »
When many classes from the same namespace are being used at the same
time, it is easier to use the namespace keyword:
Example
Use classes from the Html namespace without the need for the Html\qualifier:
namespace Html;
$table = new Table();
$row = new Row();
Try it Yourself »
Namespace Alias
It can be useful to give a namespace or class an alias to make it easier to write.
This is done with the use keyword:
Example
Give a namespace an alias:
use Html as H;
$table = new H\Table();
Try it Yourself »
Example
Give a class an alias:
use Html\Table as T;
$table = new T();