Courses/ Laravel

Laravel Tutorial

What is Laravel

Laravel is a free and open-source PHP-based web framework for building web applications. It was created by Taylor Otwell and intended for the development of web applications following the model–view–controller architectural pattern and based on Symfony.

Initial release date: June 2011.

Stable release: 11.1.3 / 9 July 2024;

Why Laravel?

There are a variety of tools and frameworks available to you when building a web application. However, we believe Laravel is the best choice for building modern, full-stack web applications.

Advantages of Laravel

Laravel offers you the following advantages-

  • namespaces
  • interfaces - It includes namespaces and interfaces, thus helps to organize and manage resources.
  • Composer-

Composer is a tool which includes all the dependencies and libraries. It allows a user to create a project with respect to the mentioned framework (for example, those used in Laravel installation). Third party libraries can be installed easily with help of composer.

All the dependencies are noted in composer. Json file which is placed in the source folder.

Artisan-

Command line interface used in Laravel is called Artisan. It includes a set of commands which assists in building a web application. These commands are incorporated from Symphony framework, resulting in add-on features in Laravel 5.1.

 

Features of Laravel

Laravel offers the following key features which makes it an ideal choice for designing web applications −

Modularity

Laravel provides 20 built in libraries and modules which helps in enhancement of the application. Every module is integrated with Composer dependency manager which eases updates.

Testability

Laravel includes features and helpers which helps in testing through various test cases. This feature helps in maintaining the code as per the requirements.

Routing

Laravel provides a flexible approach to the user to define routes in the web application. Routing helps to scale the application in a better way and increases its performance.

Configuration Management

A web application designed in Laravel will be running on different environments, which means that there will be a constant change in its configuration. Laravel provides a consistent approach to handle the configuration in an efficient way.

Query Builder and ORM

Laravel incorporates a query builder which helps in querying databases using various simple chain methods. It provides ORM (Object Relational Mapper) and ActiveRecord implementation called Eloquent.

Schema Builder

Schema Builder maintains the database definitions and schema in PHP code. It also maintains a track of changes with respect to database migrations.

Template Engine

Laravel uses the Blade Template engine, a lightweight template language used to design hierarchical blocks and layouts with predefined blocks that include dynamic content.

E-mail - Laravel includes a mail class which helps in sending mail with rich content and attachments from the web application.

Authentication

User authentication is a common feature in web applications. Laravel eases designing authentication as it includes features such as register, forgot password and send password reminders.

Redis

Laravel uses Redis to connect to an existing session and general-purpose cache. Redis interacts with session directly.

Queues

Laravel includes queue services like emailing large number of users or a specified Cron job. These queues help in completing tasks in an easier manner without waiting for the previous task to be completed.

Event and Command Bus

Laravel 5.1 includes Command Bus which helps in executing commands and dispatch events in a simple way. The commands in Laravel act as per the application’s lifecycle.

 

Laravel Interview Question

Questions Index

  1. What is Composer in Laravel
  2. What is Artisan
  3. What is a Facade
  4. What are Contracts
  5. What is Eloquent
  6. What is ORM (Object-Relational Mapping)
  7. What is Seeding
  8. What is Throttling
  9. What is Scaffolding
  10. What is SQL Injection Prevention
  11. What is the Laravel Request Life Cycle
  12. What are Service Providers
  13. What is the Service Container
  14. What is Dependency Injection
  15. What is the Singleton Design Pattern
  16. Cache in Laravel (Redis, Memcached)
  17. What is the Default File in Laravel
  18. What are Routes
  19. What is Reverse Routing
  20. What is Middleware
  21. What is Authorization and Authentication
  22. What are Migrations
  23. What are Seeders and Factories
  24. What are Relationships in Laravel
  25. What is Normalization in Laravel
  26. What are Accessors and Mutators
  27. What are Cookies and Sessions and Their Uses
  28. How to Use Cookies on the Server Side
  29. How to Identify a Session When the Same User Logs in from Two Browsers
  30. What is the Default Session Time
  31. What are Error Handlers and How Many Types Are There
  32. Why Use Try and Catch for Error Handling
  33. What is the Difference Between require and require_once
  34. What is the Difference Between GET and POST Methods and What is the Size Limit for GET Requests
  35. What is Local Storage
  36. What are CSRF Tokens and How to Enable Them
  37. What is Cross-Site Scripting (XSS) and How to Prevent It
  38. How to Enable Caching
  39. How to Put a Site in Maintenance Mode
  40. How to Enable Logging
  41. What are Mutators and Accessors
  42. What is Laravel Breeze
  43. What is Laravel Passport

 

Basic to Intermediate Questions

  1. What are the key features of Laravel?
  2. Explain the MVC architecture in Laravel.
  3. What is Eloquent ORM and how does it work in Laravel?
  4. How do you create a new Laravel project?
  5. What is a Service Provider and how does it work in Laravel?
  6. How does Laravel’s routing system work?
  7. Explain the purpose of middleware in Laravel.
  8. How do you handle validation in Laravel?
  9. What are Laravel Facades and how do they work?
  10. How does Laravel handle database migrations?
  11. What are Laravel’s built-in authentication features?
  12. How can you implement custom validation rules in Laravel?
  13. What is a Laravel Job and how do you use it?
  14. How does Laravel's dependency injection work?
  15. What is a Laravel Policy and how do you use it?
  16. Explain the purpose of Laravel's config files.
  17. How does Laravel’s query builder differ from Eloquent ORM?
  18. What is the purpose of Laravel’s artisan command-line tool?
  19. How do you handle file uploads in Laravel?
  20. Explain Laravel’s Blade templating engine.

Advanced Questions

  1. What are Laravel Events and Listeners, and how do you use them?
  2. How does Laravel support testing? Describe the types of tests you can write.
  3. What is Laravel’s approach to caching, and how do you configure it?
  4. Explain Laravel’s queue system and how it handles background tasks.
  5. How do you manage API rate limiting in Laravel?
  6. What are Laravel Policies and Gates, and how do they differ?
  7. Describe how you would handle database transactions in Laravel.
  8. What is Laravel’s approach to localization and how do you use it?
  9. How do you implement and manage Laravel’s custom Artisan commands?
  10. Describe Laravel’s security features, such as CSRF protection and encryption.
  11. How does Laravel handle database seeding and factories?
  12. What are Laravel's scheduled tasks and how do you configure them?
  13. Explain the concept of Laravel's Service Container and how it’s used for Dependency Injection.
  14. How do you implement real-time features in Laravel applications (e.g., broadcasting)?
  15. What are some performance optimization techniques in Laravel?
  16. How do you handle multiple database connections in Laravel?
  17. Explain Laravel’s “Repositories” pattern and how you would implement it.
  18. How do you use Laravel’s built-in support for Redis and caching?
  19. Describe how you would create and use Laravel’s custom helper functions.
  20. What are some best practices for structuring a large Laravel application?

Expert-Level Questions

  1. How do you manage and optimize Laravel's database queries for performance?
  2. What are Laravel’s advanced features for API development (e.g., Passport, Sanctum)?
  3. Describe how you would debug a complex Laravel application.
  4. How do you implement multi-tenancy in a Laravel application?
  5. What are Laravel’s policies for API security and how do you implement them?
  6. How do you use Laravel’s dependency injection container for complex scenarios?
  7. What strategies do you use for managing Laravel’s migrations in a team environment?
  8. Explain how you would use Laravel’s event broadcasting with WebSockets.
  9. Describe Laravel’s integration with front-end frameworks (e.g., Vue.js, React).
  10. How do you handle Laravel application deployment and environment configuration?

key features of Laravel:

  1. Eloquent ORM (Object-Relational Mapping): Laravel’s ORM provides an intuitive and powerful way to interact with databases. Eloquent allows developers to work with database records as if they were objects, making database operations simpler and more readable.
  2. Blade Templating Engine: Blade is Laravel’s built-in templating engine. It allows for the use of PHP code within views and includes features like template inheritance and sections, making it easier to manage and structure views.
  3. Routing: Laravel offers a flexible and expressive routing system that allows developers to define routes for their application using a simple and readable syntax.
  4. Artisan Command-Line Interface: Artisan is Laravel’s command-line tool that helps automate common tasks, such as database migrations, seeding, and running tests. It enhances productivity and simplifies development workflows.
  5. Middleware: Middleware provides a way to filter HTTP requests entering your application. It can be used for tasks like authentication, logging, and modifying requests or responses.
  6. Database Migration & Seeding: Laravel’s migration system allows you to version control your database schema, making it easy to modify and share schema changes. Seeding helps populate the database with sample data for testing and development.
  7. Authentication & Authorization: Laravel provides built-in support for user authentication and authorization, including features like registration, login, password resets, and user roles and permissions.
  8. Security: Laravel includes various security features such as encryption, hashing, and protection against common web vulnerabilities like SQL injection and cross-site request forgery (CSRF).
  9. Task Scheduling: The framework has a built-in task scheduling system that allows you to define scheduled tasks within your application using a clean and expressive syntax.
  10. Testing: Laravel supports automated testing using PHPUnit, making it easier to write and run tests for your application. It includes features like test helpers and support for HTTP, database, and unit tests.
  11. Laravel Ecosystem: Laravel has a rich ecosystem with tools and packages such as Laravel Forge (for server management), Laravel Vapor (serverless deployment), and Laravel Nova (admin panel), which extend its capabilities.
  12. Queue Management: Laravel provides a unified API for various queue backends, allowing you to defer the processing of time-consuming tasks, like sending emails, to improve application performance.
  13. Local Development Environment: Laravel Homestead is an official Vagrant box that provides a consistent development environment, which includes all necessary tools and software to develop Laravel applications.

What is a Service Provider and how does it work in Laravel

  • Service Provider is a central concept used to bind classes into the service container and configure the various services of the application.
  • Service providers are responsible for bootstrapping and registering application services.

How Service Providers Work

Registration: Service providers are where you bind classes and services into the service container. This is done in the register method of the provider.

public function register(){

    $this->app->bind('SomeService', function ($app) {       return new SomeService();  

 });}

Bootstrapping: After services are registered, the boot method of the provider is called. This method is used for any initialization that needs to occur after all services have been registered.

public function boot()

{

    // Code to run after all services are registered

}

Key Points About Service Providers

Service Container Integration: Service providers are integral to Laravel’s service container, allowing you to manage class dependencies and perform dependency injection.

Automatic Loading: Laravel automatically loads service providers listed in the config/app.php configuration file. This file includes a list of all the providers that should be loaded when the application starts.

Custom Providers: You can create custom service providers by running the Artisan command php artisan make:provider CustomServiceProvider. This generates a new provider class where you can define your bindings and bootstrapping logic.

 

Answers Index

  1. What is composer in Laravel

A Composer is a tool that incorporates all the dependencies and libraries. It helps the client to create a project with respect to its specified system and project. Third-party libraries can be installed in a project effortlessly utilizing composer.

  1. What is artisans

Artisan is the name of the command-line interface included with Laravel.

It provides a number of helpful commands for our use while developing application.

It is driven by the powerful Symfony Console component. To view a list of all available Artisan commands, you may use the list command: php artisan list.

  1. What is façade

Façade is a way to access non static function as like static function by using :: operator

There are lots of facades aval in Laravel ex- Auth::user(), DB::table(“users”), Cache::put(),  Log::info(“logging”), Route :: get(), View::make(“home”).

  1. What is contracts

Laravel's Contracts are a set of interfaces that define the core services provided by the framework.

For example, a Queue contract defines the methods needed for queueing jobs,

while the Mailer contract defines the methods needed for sending e-mail.

  1. What is Eloquent

Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.

  1. What is ORM
  2. What is seed
  • Laravel includes the ability to seed your database with data using seed classes. All seed classes are stored in the database/seeders directory.
  • To generate a seeder, execute the make:seeder Artisan command. All seeders generated by the framework will be placed in the database/seeders directory:

php artisan make:seeder UserSeeder

A seeder class only contains one method by default: run. This method is called when the db:seed Artisan command is executed. Within the run method, you may insert data into your database however you wish. You may use the query builder to manually insert data or you may use Eloquent model factories.

 

  1. What is throttling
  • The throttle middleware is made to protect routes against excessive reception of too many HTTP requests and restricting them once a limit has been reached.

 

  1. What is scaffold
  2. What is prevent sql injection
  3. What is Laravel Request Life Cycle
  4. What is service providers

    It’s a inbuild class that’s are aval in confi/app.php file with keyword ‘providers’ example – Auth, Cache, Cookie, Session, database, pagination, encryption, filesystem, mail, hashing and more it will automatically load while load the composer and create object for that class.

  1. We can create our own providers under app/providers. Using artisan cli->

 php artisa make : provider providername

  1. after creating provider I have to register providername under config/app.php file in ‘providers’ key
  1. What is service container

 Service container is a way of manage the object of service providers that should not create manytime, create object of class  only one time and use it every time, it help in memory management , easy to change in code and easy to test.

  1. dependency injection

 Laravel, dependency injection is the process of injecting class dependencies into a class through a constructor or setter method.

  1. What is Singleton design pattern

Step 1: Create a Singleton Class

Define your singleton class. For example, let's create a simple Logger class that should only have one instance.

namespace App\Services;

 

class Logger

{

    protected static $instance = null;

 

    private function __construct()

    {

        // Initialize the logger (e.g., open file, etc.)

    }

 

    public static function getInstance()

    {

        if (self::$instance === null) {

            self::$instance = new self();

        }

 

        return self::$instance;

    }

 

    public function log($message)

    {

        // Log the message

    }

 

    private function __clone()

    {

        // Prevent cloning

    }

 

    private function __wakeup()

    {

        // Prevent unserialization

    }

}

Step 2: Register Singleton in a Service Provider

Laravel's service container supports singletons. To register a singleton, you can use a service provider. For example, let's create a service provider to register our Logger class.

namespace App\Providers;

 

use Illuminate\Support\ServiceProvider;

use App\Services\Logger;

 

class LoggerServiceProvider extends ServiceProvider

{

    public function register()

    {

        $this->app->singleton(Logger::class, function ($app) {

            return Logger::getInstance();

        });

    }

}

Step 3: Register the Service Provider

Add the service provider to your config/app.php file:

'providers' => [

    // Other Service Providers

 

    App\Providers\LoggerServiceProvider::class,

],

 

  1. cache in laravel (redis, memcached)
  2. what is default file in Laravel
  3. What is routes
  4. What is revers routing

Reverse routing is a feature of Laravel that allows developers to generate URLs dynamically based on the names of their routes.

In simple terms, reverse routing in Laravel is the process of generating URLs based on named routes or controller actions. It is the opposite of defining a route to respond to HTTP requests. Reverse routing allows developers to create links to named routes and keep the URL structure consistent throughout the project. This way, if you decide to change your URL at some point, you only need to modify the routes file instead of manually changing every instance of the URL throughout your application.

Here’s how you might define a route for a user’s profile:

Route::get('user/profile', function () {
    // Your logic here
})->name('profile');

Once you have a named route, you can generate URLs to that route using the global route function:

$url = route('profile');

This would generate a URL like http://your-app.com/user/profile.

 

  1. What is middleware
  2. What is authorization and authentication
  3. What is migration
  4. What is Seeders and Factories
  5. What is Relationship in Laravel
  6. What is normalization in Laravel
  7. What is Accessors and Mutators
  8. What is cookies and session and uses
  9. How to use cookies in server side
  10. How to identified session while same user login in two browsers
  11. What is session default time
  12. What is errors handlers and how many type of errors handler
  13. Why use try and catch error handlers
  14. What difference between require and required once
  15. What difference between Get and Post and what limit size of get method
  16. What is local storage
  17. What is csrf tokens and how enable
  18. What is crosssite scripting and how to stop
  19. How to enable cashed
  20. How to make site in maintenance mode
  21. How to enable logs
  22. Mutators and Accessors

 You can use Eloquent mutators and accessors to automatically format data when it is set or retrieved from the database.

// In your Eloquent model

public function setNameAttribute($value)

{

    $this->attributes['name'] = ucfirst(strtolower($value));

}

 

public function getNameAttribute($value)

{

    return ucfirst($value);

}

 

  1. What is Laravel Breeze

Laravel Breeze is a minimal, simple implementation of all of Laravel's authentication features, including login, registration, password reset, email verification, and password confirmation. In addition, Breeze includes a simple "profile" page where the user may update their name, email address, and password.

Oops interview question

Questions Index

  1. What is inheritance
  2. What is polymorphism
  3. What is Abstract class
  4. What is Interface class
  5. What is encapsulation
  6. What is access modifier
  7. What is Static class
  8. What is magic function
  9. What is constructor
  10. What is destructor

Answers Index

  1. What is inheritance
  2. What is polymorphism
  3. What is Abstract class
  4. What is Interface class
  5. What is encapsulation
  6. What is access modifier
  7. What is Static class
  8. What is magic function
  9. What is constructor
  10. What is destructor

 

JavaScript Interview Questions

Questions Index

  1. What is Dom
  2. What is synchronous and asynchronous behaviour
  3. What is events listener
  4. What is callback function
  5. What Difference between let and var

Answers Index

  1. What is Dom
  2. What is synchronous and asynchronous behaviour
  3. What is events listener
  4. What is callback function
  5. What Difference between let and var

 

 

Database Interview Questions

Questions Index

  1. How many types of search engines in database
  2. Types of Keys in Relational Model
  3. What is view in databases
  4. Indexing in database
  5. What is Relationships in dbms
  6. What is database engines and its type
  7. What difference between MySQL and PostgreSQL
  8. what is difference between truncate and delete and drop
  • DROP command in SQL removes the table from the database,
  • DELETE command removes one or more records from the table,
  • TRUNCATE command removes all the rows from the existing table.
  1. SQL Commands | DDL, DQL, DML, DCL and TCL Commands
  2. What difference between SQL and DBMS and rdbms
  3. What is triggers in SQL

A trigger is a stored procedure in a database that automatically invokes whenever a special event in the database occurs. For example, a trigger can be invoked when a row is inserted into a specified table or when specific table columns are updated.

Database Answers Index

  1. How many types of search engines in database
  2. Types of Keys in Relational Model

Keys are one of the basic requirements of a relational database model. It is widely used to identify the tuples(rows) uniquely in the table. We also use keys to set up relations amongst various columns and tables of a relational database.

Different Types of Database Keys

Candidate Key

Primary Key

Super Key

Alternate Key

Unique Key

Foreign Key

Composite Key

Candidate Key

The minimal set of attributes that can uniquely identify a tuple is known as a candidate key. For Example, STUD_NO in STUDENT relation. 

  • Every table must have at least a single candidate key.
  • A table can have multiple candidate keys but only one primary key.
  • The value of the Candidate Key is unique and may be null for a tuple.
  • There can be more than one candidate key in a relationship. 

 

Primary Key

There can be more than one candidate key in relation out of which one can be chosen as the primary key.

 

  • It is a unique key.
  • It can identify only one tuple (a record) at a time.
  • It has no duplicate values, it has unique values.
  • It cannot be NULL.
  • Primary keys are not necessarily to be a single column; more than one column can also be a primary key for a table.

Super Key

The set of attributes that can uniquely identify a tuple is known as Super Key. A super key is a group of single or multiple keys that identifies rows in a table. It supports NULL values. 

  • Adding zero or more attributes to the candidate key generates the super key.
  • A candidate key is a super key but vice versa is not true.
  • Super Key values may also be NULL.

Alternate Key

  • The candidate key other than the primary key is called an alternate key.
  • All the keys which are not primary keys are called alternate keys.
  • It is a secondary key.
  • It contains two or more fields to identify two or more records.
  • These values are repeated.
  • Eg:- SNAME, and ADDRESS is Alternate keys

 

Foreign Key

If an attribute can only take the values which are present as values of some other attribute, it will be a foreign key to the attribute to which it refers. The relation which is being referenced is called referenced relation and the corresponding attribute is called referenced attribute. The referenced attribute of the referenced relation should be the primary key to it.

  • It is a key it acts as a primary key in one table and it acts as 
    secondary key in another table.
  • It combines two or more relations (tables) at a time.
  • They act as a cross-reference between the tables.
  • For example, DNO is a primary key in the DEPT table and a non-key in EMP

Composite Key

Sometimes, a table might not have a single column/attribute that uniquely identifies all the records of a table. To uniquely identify rows of a table, a combination of two or more columns/attributes can be used.  It still can give duplicate values in rare cases. So, we need to find the optimal set of attributes that can uniquely identify rows in a table.

  • It acts as a primary key if there is no primary key in a table
  • Two or more attributes are used together to make a composite key.
  • Different combinations of attributes may give different accuracy in terms of identifying the rows uniquely.

Unique Key

 

Difference Between Primary Key and Unique Key

Primary Key

Unique Key

A primary key cannot have a NULL value.

Unique keys can have one NULL value.

The table can have only one primary key.

The table can have more than one unique key.

Any change in primary key value may necessitate updates in related tables to maintain referential integrity.

A unique key can be updated or deleted, it doesn’t affect the table’s integrity constraints.

In some databases, the primary key can generate a clustered index by default.

In some databases, a unique key can generate a non-clustered index by default.

 

 

 

  1. What is view in databases

Views in SQL are a kind of virtual table. A view also has rows and columns like tables, but a view doesn’t store data on the disk like a table. View defines a customized query that retrieves data from one or more tables, and represents the data as if it was coming from a single source.

We can create a view by selecting fields from one or more tables present in the database. A View can either have all the rows of a table or specific rows based on certain conditions.

Syntax

CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;

 

  1. Indexing in database

Indexing improves database performance by minimizing the number of disc visits required to fulfill a query. It is a data structure technique used to locate and quickly access data in databases.

To speed up data retrieval, the values are also kept in sorted order.

Structure of an indexing in database

search key

Data reference or pointer

 

                          value

                         A single index

Key

Attributes of Indexing

Access Types: This refers to the type of access such as value-based search, range access, etc.

Access Time: It refers to the time needed to find a particular data element or set of elements.

Insertion Time: It refers to the time taken to find the appropriate space and insert new data.

Deletion Time: Time taken to find an item and delete it as well as update the index structure.

Space Overhead: It refers to the additional space required by the index.

 

 

How to gender Update table where g=1 and g=0

 

  1. Relationships

Definition: Relationships in Laravel refer to how different models are related to each other in terms of their database structure. Laravel Eloquent ORM (Object-Relational Mapping) provides various methods to define these relationships between models.

Types of Relationships:

  • One-to-One: A single record in one table relates to a single record in another table.

php

// User.php

public function profile() {

    return $this->hasOne(Profile::class);

}

 

// Profile.php

public function user() {

    return $this->belongsTo(User::class);

}

  • One-to-Many: A single record in one table relates to multiple records in another table.

php

// Post.php

public function comments() {

    return $this->hasMany(Comment::class);

}

                                              

// Comment.php

public function post() {

    return $this->belongsTo(Post::class);

}

  • Many-to-Many: Multiple records in one table relate to multiple records in another table. This requires a pivot table.

php

Copy code

// Student.php

public function courses() {

    return $this->belongsToMany(Course::class);

}

 

// Course.php

public function students() {

    return $this->belongsToMany(Student::class);

}

  • Has Many Through: A relation through an intermediate model.

php

Copy code

// Country.php

public function posts() {

    return $this->hasManyThrough(Post::class, User::class, 'country_id', 'user_id');

}

  • Polymorphic Relations: One model can be associated with multiple other models using a single association.

php

Copy code

// Comment.php

public function commentable() {

    return $this->morphTo();

}

 

// Post.php

public function comments() {

    return $this->morphMany(Comment::class, 'commentable');

}

 

// Video.php

public function comments() {

    return $this->morphMany(Comment::class, 'commentable');

}

Key Points:

  • Purpose: To define how models relate to each other and manage data interactions efficiently.
  • Implementation: Implemented in the Eloquent ORM layer of Laravel using methods like hasOne, belongsTo, hasMany, belongsToMany, etc.
  1. What is database engines and its type

Database engines are MySQL components that can handle SQL operations like create, read, update data from a database. There are two types of engines in MySQL:  transactional and non-transactional.InnoDB is the default engine for MySQL 5.5 and above versions.

  • Transactional Databases: In this type, we can roll back the write operations on the database if they are left incomplete. These operations are known as transactions. Majorly, modern engines are transactional.
  • Non-Transactional Databases: Unlike transactional databases, they don’t provide Rollback/Commit. Instead, we need to manually code to perform the rollback operations.
  1. What difference between MySQL and PostgreSQL

 

 

 

 

Interfaces class

  • Interface support multiple inheritance
  • interface can only contain abstract function
  • In interface we cannot define variables
  • No constructor in interfaces
  • All function must be public

An interface is a contract that defines a set of methods that a class must implement. It allows you to specify what methods a class should have without providing the implementation details.

No Instantiation: Interfaces cannot be instantiated directly. They are intended to be implemented by classes.

Multiple Interfaces: A class can implement multiple interfaces, allowing it to inherit behaviours from several sources.

Method Definitions Only:

Interfaces define method signatures (name, parameters) but do not provide implementations.

 

Defining an Interface:

 

interface class1 {

    public function getPrice1();

}

interface class2 {

    public function getPrice2();

}

 

Implementing an Interface in a Class:

class Product implements class1, class2 {

    private $price;

   

    public function __construct($price) {

        $this->price = $price;

    }

   

    public function getPrice1() {

        return $this->price;

    }

public function getPrice2() {

        return $this->price;

    }

}

$product = new Product (100); //create instance

echo $product->getPrice1(); //get getPrice2 using instance, output- 100

echo $product->getPrice2(); //get getPrice2using instance, output- 100

 

Abstract class (incomplete)

  • Abstract class contain at least one abstract function
  • Abstract method must declare but not implemented
  • Abstract class could not create object
  • Abstract class, child class must contain abstract function

 

Student Feedback

4.2 /5
Average Ratings
  • ( 79% )
  • ( 30% )
  • ( 69% )
  • ( 29% )
  • ( 10% )

02 Reviews

  • Jassica Treat

    Pellentesque ultrices orci id justo vehicula, non aliquam erat lacinia Mam rem aperiam, eaque ipsa qua tore veritatis.

  • Willimes Doe

    Pellentesque ultrices orci id justo vehicula, non aliquam erat lacinia Mam rem aperiam, eaque ipsa qua tore veritatis.

Post Review