Mohamed Allam
Laravel Example

Laravel Example

PHP Object Oriented series coming soon

Mohamed Allam's photo
Mohamed Allam

Published on Jul 31, 2021

5 min read

Subscribe to my newsletter and never miss my upcoming articles

Objects basics

Objects and classes lie at the heart of this Object oriented programming, and, since the introduction of PHP 5 over a decade ago, they have lain at the heart of PHP, too. In this video, I establish the groundwork for more in-depth coverage of objects and design by examining PHP’s core object-oriented features. If you are new to object-oriented programming, you should focus carefully.

This chapter will cover the following topics:

  • Classes and objects: Declaring classes and instantiating objects.
  • Constructor methods: Automating the setup of your objects.
  • Primitive and class types: Why type matters.
  • Inheritance: Why we need inheritance and how to use it.
  • Visibility: Streamlining your object interfaces and protecting your methods and properties from meddling.

Content:

Classes and Objects

The first barrier to understanding object-oriented programming is the strange and wonderful relationship between the class and the object. For many people, it is this relationship that represents the first moment of revelation, the first flash of object- oriented excitement. So let’s not skimp on the fundamentals.

A First Class

Classes are often described in terms of objects. This is interesting, because objects are often described in terms of classes. This circularity can make the first steps in object- oriented programming hard going. Because it’s classes that shape objects, we should begin by defining a class.

In short, a class is a code template used to generate one or more objects. You declare a class with the class keyword and an arbitrary class name. Class names can be any combination of numbers and letters, although they must not begin with a number. They can also contain underscore characters. The code associated with a class must be enclosed within braces. Here, I combine these elements to build a class:

class Book
{
// class body
}

The convention is to write classes first letter of words upper case, and no underscores or anything like that.

A First Object

If a class is a template for generating objects, it follows that an object is data that has been structured according to the template defined in a class. An object is said to be an instance of its class. It is of the type defined by the class.

I use the Book class as a mold for generating Book objects. To do this, I need the new operator. The new operator is used in conjunction with the name of a class, like this:

$book1 = new Book();
$book2 = new Book();

the $book1 is called instance of class.

every object has a serial number and ID for the life cycle of the object.

Setting Properties in a Class

A property in a class looks similar to a standard variable except that, in declaring a property, you must precede the property variable with a visibility keyword. This can be public, protected, or private, and it determines the location in your code from which the property can be accessed. Public properties are accessible outside the class, for example, and private properties can only be accessed by code within the class.

class Book
{
    public $title = "PHP 8";
    public $author = "John Doe";
    public $publisher = "Mosh Pit";
    public $price = 0;
}

now if we can access properties after we instantiate the class

$book1 = new Book();
print $book1->title;
// output: PHP 8

we can play around access and assign different value for each property.

$book1 = new Book();
$book1->title = "Java";
print $book1->title;
// output: Java

or we can add non existing property to the object.

$book1 = new Book();
$book1->bookDescription = "Object oriented programming";
print $book1->bookDescription;
// output: Object oriented programming

However, this method of assigning properties to objects is not considered good practice in object-oriented programming.

Setting multiple properties on multiple objects will soon become a chore

$book1 = new Book();
$book1->title = "Surge";
$book1->author  = "Caleb";
$book1->publisher = "Valet";
$book1->price = 5.99;

$book2 = new Book();
$book2->title = "Ancestors";
$book2->author  = "John Doe";
$book2->publisher = "Jelly";
$book2->price = 9.99;
...

Another problem we might misspell or forget a property name

$book3->publishher = "Shirley";
$book3->authorName = "Jackson";

Working with Methods

Just as properties allow your objects to store data (book name, author, price..ect), methods allow your objects to perform tasks. Methods are special functions declared within a class. As you might expect, a method declaration resembles a function declaration. The function keyword precedes a method name, followed by an optional list of argument variables in parentheses. The method body is enclosed by braces.

public function myMethod($argument, $another)
{
// do something 
}

Now we can create better classes

class Book
{
    public $title = "PHP 8";
    public $author = "John Doe";
    public $publisher = "Groovy";
    public $price = 0;

    public function getBook()
    {
        return $this->title . " "
            . $this->author;
        } 
}

To call a method we use

$book1 = new Book();
$book1->title = "PHP 9";
$book1->author = "Jane Doe";
$book1->publisher = "Mosh Pit";
$book1->price = 12.99;
print $book1->getBook();

//output: PHP 9 Jane Doe

I introduce a feature in this method’s body. The $this pseudo-variable is the mechanism by which a class can refer to an object instance. If you find this concept hard to swallow, try replacing $this with the phrase “the current instance.” Consider the following statement:

$this→title

means $title property of current instance.

Creating a Constructor Method

Constructor Property Promotion

Class Book {


    public function __construct(public $name){

    }

}

$javaBook = new Book('Java');

Default Arguments and Named Arguments Arguments and Types Primitive Types Some Other Type-Checking Functions Type Declarations: Object Types Type Declarations: Primitive Types mixed Types Union Types Nullable Types Return Type Declarations Inheritance The Inheritance Problem Working with Inheritance Public, Private, and Protected: Managing Access to Your Classes Typed Properties

Advanced Features

You have already seen how class type hinting and access control give you more control over a class’s interface. In this chapter, I will delve deeper into PHP’s object-oriented features.

This chapter will cover several subjects:

  • Static methods and properties: Accessing data and functionality through classes rather than objects
  • Abstract classes and interfaces: Separating design from implementation
  • Traits: Sharing implementation between class hierarchies
  • Error handling: Introducing exceptions
  • Final classes and methods: Limiting inheritance
  • Interceptor methods: Automating delegation
  • Destructor methods: Cleaning up after your objects
  • Cloning objects: Making object copies
  • Resolving objects to strings: Creating a summary method
  • Callbacks: Adding functionality to components with anonymous functions and classes
 
Share this
Proudly part of