Php OOP v1 Basics

What is OOP?

OOP (Object Oriented Programming) is a design concept.

Why OOP?

  • As Software is developed, it becomes more complex and difficult to control.
  • The complexity and maintenance costs (time – money) of software developed with OOP are less.
  • OOP ensures the reusability of the written code and that it can be understood and developed by other developers.
  • When you learn OOP with a language that supports the OOP method, it will be easier for you to learn the OOP development method in other software languages.
  • It allows us to develop using design patterns such as MVC with PHP OOP support.
  • In large-scale companies, several different software development teams develop software, if there is no order in the code, other team members may have difficulty understanding the code. Or it will take longer for a developer new to the team to understand the code in the software and start developing it. OOP allows us to solve all these problems.
  • Thanks to our PHP OOP knowledge, we can learn and use framework structures faster.
Note: To understand OOP, you must be familiar with basic PHP concepts. 
For more information. 

Let’s take a look at the OOP features

  • Variables inside the class in which objects are defined are called properties
  • Objects can have different properties.

Let’s give an example with a student class

<?php 

class Student {

    private $StudentID = 0;
    public $StudentName = "John";
    protected $StudentDepartment = "Computer Science";

}

?>

Access modifiers that features can take

Advertisements

Public:  The public keyword enables access to the variable or method from outside the class.

public $StudentName = "John";
Note: If an access identifier is not specified, the default value is public.

Private: The private keyword prevents our variable or method from being accessed from the outside of the class. The main reason for this blocking is to prevent security vulnerabilities.

private $StudentID = 0;

Protected: Protected keyword enables class variables or methods to be used only in classes derived from the class we specify. It does not allow access from outside of the class like the private keyword.

protected $StudentDepartment = "Computer Science";
For more information.

Using the OOP Class

To use the defined class structure, an instance of it must be generated.

new: new is used to create a new object from the class.

The developer creates the class instance and the object is created.

$John = new Student();

With ‘->‘ you can access the properties in the class.

echo $John->StudentName;

PHP OOP and $this

When an object is created with PHP, the operating system keeps the information about the object in memory.

This information can be accessed externally with the variable we define the object

The developer defines an example variable, this variable stores the memory reference, and the developer accesses the object with that reference.

$John = new Student();
Note: Since the object is not created in the class in which the objects are defined, 
its memory address is unknown.

So Php defines the memory reference to the $this keyword when creating the object.

As a result, the developer uses the $this keyword to access properties and methods within the object.

$this->MethodName();

Let’s reinforce what we have told with an example

<?php 

class Student {

    private $StudentID = 0;
    public $StudentName = "";
    public $StudentSurname = "";
    protected $StudentDepartment = "";

    public function __construct($sName,$sSurname,$sDepartment)
    {
        $this->StudentName = $sName;
        $this->StudentSurname = $sSurname;
        $this->StudentDepartment = $sDepartment;
    }

    public function StudentInfo(){
        return 
        "Student Name: ". $this->StudentName . " " . $this->StudentSurname .  
        ", Department: " . $this->StudentDepartment;
    }

}

$student = new Student("John", "Doe", "Computer Science");

echo $student->StudentInfo();

?>

Constructors and Destructors

Constructors

Utilizes the constructor method (__construct), which is called automatically by PHP, to perform actions when the object is loaded.

    public function __construct()
    {
        echo "The object has been loaded into memory";
    }

Destructors

It uses the destructor method (__destruct), which is automatically called by PHP for actions to be taken while the object is deleted from memory.

    public function __destruct()
    {
     echo "The object has been deleted from memory";
    }

Let’s give an example with the student class

<?php 

class Student {
   
    private $StudentName = "";
    private $StudentSurname = "";

    public function __construct($Name, $Surname)
    {
        $this->StudentName = $Name;
        $this->StudentSurname = $Surname;
    }
}

$John = new Student("John", "Doe");

?>
Note: It is possible to open the file with the constructor method and close it 
with the destructor method in the class where the file operations are performed.
<?php 

class FileReader {
   
    private $file = null;
    private $fileName = "";
    private $fileSize = 0;

    public function __construct($fName){
        $this->fileName = $fName;
        $this->file = fopen($this->fileName, "r+");
        $this->fileSize = filesize($this->fileName);
    }

    public function readFile(){
        return fread($this->file, $this->fileSize);
    }

    public function __destruct(){
        fclose($this->file);
    }

}

$text = new FileReader("example.txt");
echo $text->readFile();

?>
Note: The use of constructor and destructor methods is not mandatory.
For more information.

PHP OOP Constants

Variables whose value we do not want to change afterward are called constant.

Example: PI (π ), e etc.

<?php 

class SampleObject {

    const PI = 3.14;

}

?>

Constants are accessed with the keyword self.

<?php 

class SampleObject {

    const PI = 3.14;

    public function printPI(){
        return self::PI;
    }

}

$sample = new SampleObject();

echo $sample->printPI();

?>
Note: We can also access constants without objects. Can be accessed with the 
containment operator (::) without creating an object. 
For more information.
<?php 

class SampleObject {

    const PI = 3.14;

}

echo SampleObject::PI;

?>
Note: Constants can also be accessed from within the derived class with the keyword parent.
<?php 

class SampleObject {

    const PI = 3.14;

}

class NewSampleObject extends SampleObject {

    public function PrintPI(){
        return parent::PI;
    }
}

$sample = new NewSampleObject();
echo $sample->PrintPI();

?>

There are some differences between constants and normal variables

  • Constant variables cannot start with $.
  • It is mandatory to assign a value after the constant variable has been created, it cannot be left blank.
  • Constant variables can have access specifiers that I explained at the beginning of the topic.
  • Constant variable cannot contain words used in Php (if, while)
  • Capital letters are often used in constant variables.
For more information. 

Static

Static declaration of class properties or methods makes this class accessible without the need to instantiate it.

Note: Unlike the Const keyword, static properties start with $ and their value can change.
static $NumberOfStudents = 0;

Static properties and methods in a class can be accessed with the self keyword.

<?php 

class Students {

    static $NumberOfStudents = 0;

    public static function GetStudents() {

        return self::$NumberOfStudents;
        
    }

    public function GetStaticMethod() {

        return self::GetStudents();
        
    }

}

?>

Static properties and methods in the class can also be accessed with the containment operator (::) without creating an object.

<?php 

class Students {

    static $NumberOfStudents = 0;

    public static function GetStudents() {

        return self::$NumberOfStudents;
        
    }

    public function GetStaticMethod() {

        return self::GetStudents();
        
    }

}

echo Students::$NumberOfStudents;
echo Students::GetStudents();

?>
When to use self over $this?
Use $this to refer to the current object. Use self to refer to the current class.
In other words, use $this->member for non-static members, 
use self::$member for static members.
Click for long answer.

Properties and methods in the class are accessed from within the derived class with the keyword parent.

<?php 

class Students {

    static $NumberOfStudents = 0;

    public static function GetStudents() {

        return self::$NumberOfStudents;
        
    }

}

class ClassPresident extends Students {

    public function GetStudentsNumber() {
        parent::$NumberOfStudents++;
        return parent::GetStudents();
    }

}

$John = new ClassPresident();

echo $John->GetStudentsNumber();
?>

Within the class, non-static properties and methods can not be accessed from the static method with the $this or self keyword.

For more information.
You can follow php.net for updates and more about PHP OOP.
https://www.php.net/manual/en/language.oop5.php
You can read my inheritance in Php, the second article of this series, here.
https://duzzii.com/php-oop-v2-inheritance/

Please report the parts you see incorrect or incomplete. And don’t forget to subscribe to our newsletter for more articles. Healthy days!


Liked it? Take a second to support Selim on Patreon!
Advertisements

Selim

Backend Developer, Öğrenci, Blogger

You may also like...

Yorum yap

%d blogcu bunu beğendi: