0% found this document useful (0 votes)
123 views

Tip: The "Don't Repeat Yourself" (DRY) Principle Is About Reducing The Repetition of Code. You

OOP stands for Object-Oriented Programming. It involves creating objects that contain both data and functions, while procedural programming focuses on writing functions that operate on data. Some key advantages of OOP include being faster and easier to execute, providing a clear structure, helping to avoid duplicated code, and making code easier to maintain and modify. Classes are templates that define properties and methods, while objects are instances of classes that can have different property values.

Uploaded by

Hestia HD
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
123 views

Tip: The "Don't Repeat Yourself" (DRY) Principle Is About Reducing The Repetition of Code. You

OOP stands for Object-Oriented Programming. It involves creating objects that contain both data and functions, while procedural programming focuses on writing functions that operate on data. Some key advantages of OOP include being faster and easier to execute, providing a clear structure, helping to avoid duplicated code, and making code easier to maintain and modify. Classes are templates that define properties and methods, while objects are instances of classes that can have different property values.

Uploaded by

Hestia HD
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

From PHP5, you can also write PHP code in an object-oriented style.

Object-Oriented programming is faster and easier to execute.

PHP What is OOP?

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or functions that perform operations on


the data, while object-oriented programming is about creating objects that contain both data
and functions.

Object-oriented programming has several advantages over procedural programming:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code and shorter
development time

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.

PHP - What are Classes and Objects?

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

So, a class is a template for objects, and an object is an instance of a class.

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.

Look at the next chapters to learn more about OOP.


A class is a template for objects, and an object is an instance of class.

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.

Objects of a class is created using the new keyword.

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 »

PHP - The $this Keyword


The $this keyword refers to the current object, and is only available inside
methods.

Look at the following example:

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 »

2. Outside the class (by directly changing the property value):

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

PHP - The __construct Function


A constructor allows you to initialize an object's properties upon creation of the
object.

If you create a __construct() function, PHP will automatically call this function


when you create an object from a class.

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

PHP - The __destruct Function


A destructor is called when the object is destructed or the script is stopped or
exited.

If you create a __destruct() function, PHP will automatically call this function at


the end of the script.

Notice that the destruct function starts with two underscores (__)!

The example below has a __construct() function that is automatically called


when you create an object from a class, and a __destruct() function that is
automatically called at the end of the script:

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

PHP - Access Modifiers


Properties and methods can have access modifiers which control where they can
be accessed.

There are three access modifiers:

 public - the property or method can be accessed from everywhere. This


is default
 protected - the property or method can be accessed within the class and
by classes derived from that class
 private - the property or method can ONLY be accessed within the class

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;

  function set_name($n) {  // a public function (default)


    $this->name = $n;
  }
  protected function set_color($n) { // a protected function
    $this->color = $n;
  }
  private function set_weight($n) { // a private function
    $this->weight = $n;
  }
}

$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.

An inherited class is defined by using the extends keyword.

Let's look at an example:

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}.";
  }
}

// Strawberry is inherited from Fruit


class Strawberry extends Fruit {
  public function message() {
    echo "Am I a fruit or a berry? ";
  }
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>
Try it Yourself »

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.

The Strawberry class also has its own method: message().

PHP - Inheritance and the Protected Access


Modifier
In the previous chapter we learned that protected properties or methods can be
accessed within the class and by classes derived from that class. What does that
mean?

Let's look at an example:

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 to call all three methods from outside class


$strawberry = new Strawberry("Strawberry", "red");  // OK. __construct()
is public
$strawberry->message(); // OK. message() is public
$strawberry->intro(); // ERROR. intro() is protected
?>

Try it Yourself »

In the example above we see that if we try to call a protected method (intro())


from outside the class, we will receive an error. public methods will work fine!

Let's look at another example:

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? ";
    // Call protected method from within derived class - OK
    $this -> intro();
  }
}
$strawberry = new Strawberry("Strawberry", "red"); // OK. __construct()
is public
$strawberry->message(); // OK. message() is public and it calls intro()
(which is protected) from within the derived class
?>

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.

PHP - Overriding Inherited Methods


Inherited methods can be overridden by redefining the methods (use the same
name) in the child 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}.";
  }
}

class Strawberry extends Fruit {


  public $weight;
  public function __construct($name, $color, $weight) {
    $this->name = $name;
    $this->color = $color;
    $this->weight = $weight;
  }
  public function intro() {
    echo "The fruit is {$this->name}, the color is {$this->color}, and
the weight is {$this->weight} gram.";
  }
}

$strawberry = new Strawberry("Strawberry", "red", 50);


$strawberry->intro();
?>

Try it Yourself »

PHP - The final Keyword


The final keyword can be used to prevent class inheritance or to prevent
method overriding.

The following example shows how to prevent class inheritance:

Example
<?php
final class Fruit {
  // some code
}

// will result in error


class Strawberry extends Fruit {
  // some code
}
?>

Try it Yourself »

The following example shows how to prevent method overriding:


Example
<?php
class Fruit {
  final public function intro() {
    // some code
  }
}

class Strawberry extends Fruit {


  // will result in error
  public function intro() {
    // some code
  }
}
?>
PHP OOP - Class Constants
PHP - Class Constants
Constants cannot be changed once it is declared.

Class constants can be useful if you need to define some constant data within a
class.

A class constant is declared inside a class with the const keyword.

Class constants are case-sensitive. However, it is recommended to name the


constants in all uppercase letters.

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.

An abstract class is a class that contains at least one abstract method. An


abstract method is a method that is declared, but not implemented in the code.

An abstract class or method is defined with the abstract keyword:

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!";
  }
}

// Create objects from the child classes


$audi = new audi("Audi");
echo $audi->intro();
echo "<br>";

$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).

Traits are declared with the trait keyword:

Syntax
<?php
trait TraitName {
  // some code...
}
?>

To use a trait in a class, use the use keyword:

Syntax
<?php
class MyClass {
  use TraitName;
}
?>

Let's look at an example:


Example
<?php
trait message1 {
public function msg1() {
    echo "OOP is fun! ";
  }
}

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.

PHP - Using Multiple Traits


Let's look at another example:

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.

Static methods are declared with the static keyword:

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();

Let's look at an example:

Example
<?php
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }
}

// Call static method


greeting::welcome();
?>
Try it Yourself »

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).

PHP - More on Static Methods


A class can have both static and non-static methods. A static method can be
accessed from a method in the same class using the self keyword and double
colon (::):

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.

Static properties are declared with the static keyword:

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;

Let's look at an example:

Example
<?php
class pi {
  public static $value = 3.14159;
}

// Get static property


echo pi::$value;
?>

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).

PHP - More on Static Properties


A class can have both static and non-static properties. A static property can be
accessed from a method in the same class using the self keyword and double
colon (::):

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;
  }
}

// Get value of static property directly via child class


echo x::$value;

// or get value of static property via xStatic() method


$x = new x();
echo $x->xStatic();
?>
PHP Namespaces
❮ PreviousNext ❯

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;

Note: A namespace declaration must be the first thing in the PHP file. The


following code would be invalid:

<?php
echo "Hello World!";
namespace Html;
...
?>

Constants, classes and functions declared in this file will belong to


the Html namespace:

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 »

For further organization, it is possible to have nested namespaces:

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();

You might also like