CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

27 October, 2018

PHP Object-Oriented Programming Beginner's Guide

 Programing Coderfunda     October 27, 2018     oop's, oops, php     No comments   

PHP Object-Oriented Programming Beginner's Guide

Basic concepts around Object-Oriented Programming

Class vs Object

Class is like your house blueprint. Before your house is constructed, there is a house blueprint. It is not an actual house, but a plan how this house will look like, how many rooms it will have and so on. Then the house will be constructed by following the blueprint exactly. In this analogy, the house blueprint is a class and your actual house is an object. We can have unlimited objects of a class, just like we can build unlimited exact houses by following the same house blueprint.
A few key points to keep in mind:
  • Class is generic, whereas Object is specific
  • Class defines properties/functions of an Object
  • Object is an instance of a Class
  • You can instantiate an object, but not a Class


PHP Class

Class is consist of properties and methods. Below is a PHP class. In this simple class. $postCode is a property and ringBell() is a method. They are all prefixed with a visibility keyword (public).
Class House {

 public $postCode = “560121”;

 public function ringBell() {
  echo “Ding Dang Dong”;
 }
}
                    
To instantiate an object of a class, use the keyword new as below:
$house = new House();


Visibility

Each method and property has its visibility. There are three types of visibility in PHP. They are declared by keywords public, protected and private. Each one of them controls how a method/property can be accessed by outsiders.
Public: It allows anyone from outside access its method/property. This is the default visibility in PHP class when no keywords are prefixed to a method/property.
Protected: It only allows itself or children classes to access its method/property.
Private: It does not allow anyone except itself to access its method/property.

Inheritance

It lets subclass inherits characteristics of the parent class. Parent class decides what and how its properties/methods to be inherited by declared visibility.
class Shape {
 public function name() {
  echo "I am a shape";
 }
}

class Circle extends Shape {

}

$circle = new Circle();
$circle->name(); // I am a shape
                    
The key word here is extends. When Circle class extends from Shapeclass, it inherits all of the public and protected methods as well as properties from Shape class.


Polymorphism

The provision of a single interface to entities of different types. Basically it means PHP is able to process objects differently depending on their data type or class. This powerful feature allows you to write interchangeable objects that sharing the same interface.
interface Shape {
 public function name();
}

class Circle implements Shape {
 public function name() {
  echo "I am a circle";
 }
}

class Triangle implements Shape {
 public function name() {
  echo "I am a triangle";
 }
}

function test(Shape $shape) {
 $shape->name();
}

test(new Circle()); // I am a circle
test(new Triangle()); // I am a triangle
                    
Above example, test(Shape $shape) function declares(type hints) its only parameter to be Shape type. This function is not aware of Circle and Triangle classes. When either class is passed to this function as a parameter, it processes respectively.

Encapsulation

Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties' direct access to them. It is a concept that motivates us to think through a method/class responsibility and hide its internal implementation/details accordingly. This will make it easy to modify the internal code in a long run without affecting other part of the system. Visibility is the mechanism for encapsulation.
class Person {
 private $name;

 public function setName($name) {
  $this->name = $name;
 }

 public function getName($name) {
  return $this->name;
 }
}

$robin = new Person();
$robin->setName('Robin');
$robin->getName();
                    
In this simple class above. Field $name is encapsulated (private). Users of the class is not aware how $name is stored in Person class. Right now the $name is stored in memory. We can modify internal code of Person class to store it to a flat file or event a database. Users of the class will not need to change any code, in fact they do not even know how $name is stored, because that is encapsulated and hided from them.

Abstraction

Abstraction is the concept of moving the focus from the details and concrete implementation of things, to the types of things (i.e. classes), the operations available (i.e. methods), etc, thus making the programming simpler, more general, and more abstract. It is like a generalization instead of a specification.
class TV {
 private $isOn = false;

 public function turnOn() {
  $this->isOn = true;
 }

 public function turnOff() {
  $this->isOn = false;
 }
}

$tv = new TV();
$tv->turnOn();
$tv->turnOff();
                    
Code above defined an TV class. We can not do much with it except turning it on and off. The class TV is an abstraction of a real TV in a very simple use case.

Interface vs Abstract class

Interface

Interface declares what methods a class must have without having to implement them. Any class that implements the interface will have to implement details of those declared methods. Interface is not a class, so you can not instantiate an interface. It is useful when you need to enforce some classes to do something.
interface Vehicle {
 public function startEngine();
}

class Car implements Vehicle {
 public function startEngine() {
  echo "Engine Started";
 }
}
                    
Vehicle is an interface with a declared method startEngine(). Carimplements Vechicle, so it has to implement what startEngine() method does.

Abstract class

Abstract class is able to enforce subclasses to implement methods similar to interface. When a method is declared as abstract in an abstract class, its derived classes must implement that method.
However it is very different from interface. You can have normal properties and methods as a normal class, because it is in fact a class, so it can be instantiated as a normal class.
abstract class Vehicle {
 abstract public function startEngine();

 public function stopEngine() {
  echo "Engine stoped";
 }
}

class Car extends Vehicle {
 public function startEngine() {
  echo "Engine Started";
 }
}
                    
Vehicle is an abstract class. Car extends Vechicle, so it has to implement what startEngine() method does, because this method is declared as abstract. However Car does not have to anything with method stopEngine(), it is inherited as a normal class does.

The End Guys.

  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook

Related Posts:

  • Manage Kubernetes Clusters with PHP and Laravel Laravel PHP K8s is a package that provides access to features offered by the excellent renoki-co/php-k8s package in Laravel. The underlying PHP… Read More
  • Laravel Blade Sortable Laravel Blade Sortable provides custom blade components to add sortable, drag-and-drop HTML elements in your Laravel apps. This package uses S… Read More
  • Friendly Prefix IDs for Eloquent ModelsLaravel Prefixed IDs is a package by Spatie that automatically adds a friendly prefixed ID to Laravel models. As Freek Van der Herten describes in his… Read More
  • Firebase Cloud Messaging for Laravel Larafirebase is a package by Gentrit Abazi that provides sending push notifications and custom messages with Firebase in Laravel applications. T… Read More
  • Laravel Themer package: add multi-theme support for Laravel applicationThis Laravel Themer package adds multi-theme support to your Laravel application. It also provides a simple authentication scaffolding and presets fo… Read More
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Spring boot app (error: method getFirst()) failed to run at local machine, but can run on server
    The Spring boot app can run on the online server. Now, we want to replicate the same app at the local machine but the Spring boot jar file f...
  • Log activity in a Laravel app with Spatie/Laravel-Activitylog
      Requirements This package needs PHP 8.1+ and Laravel 9.0 or higher. The latest version of this package needs PHP 8.2+ and Laravel 8 or hig...
  • Vue3 :style backgroundImage not working with require
    I'm trying to migrate a Vue 2 project to Vue 3. In Vue 2 I used v-bind style as follow: In Vue 3 this doesn't work... I tried a...
  • Laravel auth login with phone or email
          <?php     Laravel auth login with phone or email     <? php     namespace App \ Http \ Controllers \ Auth ;         use ...
  • Enabling authentication in swagger
    I created a asp.net core empty project running on .net6. I am coming across an issue when I am trying to enable authentication in swagger. S...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh - 9/21/2024
  • pyspark XPath Query Returns Lists Omitting Missing Values Instead of Including None - 9/20/2024
  • SQL REPL from within Python/Sqlalchemy/Psychopg2 - 9/20/2024
  • MySql Explain with Tobias Petry - 9/20/2024
  • How to combine information from different devices into one common abstract virtual disk? [closed] - 9/20/2024

Laravel News

  • Locale-aware Number Parsing in Laravel 12.15 - 5/21/2025
  • Handle Fluent Values as Arrays with Laravel's array() Method - 5/18/2025
  • Chargebee Starter Kit for Billing in Laravel - 5/20/2025
  • Streamline Pipeline Cleanup with Laravel's finally Method - 5/18/2025
  • Validate Controller Requests with the Laravel Data Package - 5/19/2025

Copyright © 2025 CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda