Trending November 2023 # Php Object Oriented Programming (Oops) Concept Tutorial With Example # Suggested December 2023 # Top 16 Popular

You are reading the article Php Object Oriented Programming (Oops) Concept Tutorial With Example updated in November 2023 on the website Cancandonuts.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested December 2023 Php Object Oriented Programming (Oops) Concept Tutorial With Example

What is OOPs?

Object Oriented is an approach to software development that models application around real world objects such as employees, cars, bank accounts, etc. A class defines the properties and methods of a real world object. An object is an occurrence of a class.

The three basic components of object orientation are;

Object oriented analysis – functionality of the system

Object oriented designing – architecture of the system

Object oriented programming – implementation of the application

Object Oriented Programming Principles

The three major principles of OOP are;

Encapsulation – this is concerned with hiding the implementation details and only exposing the methods. The main purpose of encapsulation is to;

Reduce software development complexity – by hiding the implementation details and only exposing the operations, using a class becomes easy.

Protect the internal state of an object – access to the class variables is via methods such as get and set, this makes the class flexible and easy to maintain.

The internal implementation of the class can be changed without worrying about breaking the code that uses the class.

Inheritance – this is concerned with the relationship between classes. The relationship takes the form of a parent and child. The child uses the methods defined in the parent class. The main purpose of inheritance is;

Re-usability– a number of children, can inherit from the same parent. This is very useful when we have to provide common functionality such as adding, updating and deleting data from the database.

Polymorphism – this is concerned with having a single form but many different implementation ways. The main purpose of polymorphism is;

Simplify maintaining applications and making them more extendable.

OOPs Concepts in PHP

PHP is an object oriented scripting language; it supports all of the above principles. The above principles are achieved via;

Encapsulation – via the use of “get” and “set” methods etc.

Inheritance – via the use of extends keyword

Polymorphism – via the use of implements keyword

Now that we have the basic knowledge of OOP and how it is supported in PHP, let us look at examples that implement the above principles

What is UML?

Unified Modeling Language UML is a technique used to design and document object oriented systems.

UML produces a number of documents, but we will look at the class diagram which is very important to object oriented php programming.

Class Diagram Example

Class Diagram Key

The Upper box contains the class name

The middle box contains the class variables

The lower box contains the class methods

The minus (-) sign means private scope

The plus (+) sign means public scope

The hash (#) sign means protected scope

How to Create a class in PHP

The class keyword is used to define a class in PHP. Below are the rules for creating a class in PHP.

The class name should start with a letter

The class name cannot be a PHP reserved word

The class name cannot contain spaces

Let’s say we want to create a class for representing animals.

We will start with identifying the features that are common to all animals.

All animals belong to a family such as a herbivore, carnival, etc.

All animals eat food

The diagram below shows the diagram for the animal

Let’s now code our animal class

<?php class Animal { private $family; private $food; public function __construct($family, $food) { } public function get_family() { } public function set_family($family) { } public function get_food() { } public function set_food($food) { } }

HERE,

“private $family, $food” means the variables cannot be accessed directly outside the class (Encapsulation).

“public function __construct($family…)” is the php constructor method. This function is called whenever an instance of the class has been created. In this case, we are setting the family and food.

“public function get…()” is the method used to access the family or food value (Encapsulation)

“public function set…()” is the method used to set the family or food value (Encapsulation)

How implement Inheritance in PHP

We will work with a cow and a lion. Both the cow and lion inherit from the Animal class.

The class diagram below shows the relationships.

Note the cow inherits from the animal class and defines its own variable and methods too.

Let’s now code the Cow class

<?php class Cow extends Animal { private $owner; public function __construct($family, $food) { parent::__construct($family, $food); } public function set_owner($owner) { } public function get_owner() { } }

Let’s now code the Lion class

<?php class Lion extends Animal { public function __construct($family, $food) { parent::__construct($family, $food); } }

HERE,

“class … extends Animal” makes the cow and lion use methods from the Animal class (Inheritance).

How to Create object of the class

The Animal, Cow, and Lion classes should all be in the same directory for simplicity’s sake.

Let’s now create the application that uses our classes.

PHP Class Example

<?php require 'Animal.php'; require 'Cow.php'; require 'Lion.php'; $cow = new Cow('Herbivore', 'Grass'); $lion = new Lion('Canirval', 'Meat');

Testing our application

Let’s now view our application in a web browser

.

Fantastic right! Let’s now look at the third principle of OOP, polymorphism.

Let’s say we want to develop an application that connects to different database engines such as MySQL and SQL Server but use the same uniform interface.

We can create an interface that defines the standard methods and an abstract class that implements the common methods.

Interface – it is similar to a class. It only defines the methods and parameters.

Abstract class – it is a class that cannot be used to create an object directly. Its purpose is to provide partial or whole implementations of common methods.

The class diagram below illustrates the relationship among our abstract class, interface, and implementation classes.

Let’s now create our abstract class

<?php abstract class DBCommonMethods { private $host; private $db; private $uid; private $password; public function __construct($host, $db, $uid, $password) { } }

HERE,

“abstract class” means the class cannot be used directly to php create object

“$host,$db…” are class variables common to all implementations

“function __construct(…)” is the php class constructor method that sets the common variables values at initialization

Let’s now create the interface that contains the standard methods which will be implemented differently depending on the database engine.

<?php interface DBInterface { public function db_connect(); public function insert($data); public function read($where); public function update($where); public function delete($where); }

HERE,

“interface” is the keyword for creating interfaces

“public function…(…)” are the standard methods that should be implemented

Let’s now create the concrete classes that will extend the DBCommonMethods class and extend the DBInterface interface. MySQLDriver.php

<?php class MySQLDriver extends DBCommonMethods implements DBInterface { public function __construct($host, $db, $uid, $password) { parent::__construct($host, $db, $uid, $password); } public function db_connect() { public function delete($where) { public function insert($data) { public function read($where) { public function update($where) {

MSSQLServerDriver.php

<?php class MSSQLServerDriver extends DBCommonMethods implements DBInterface { public function __construct($host, $db, $uid, $password) { parent::__construct($host, $db, $uid, $password); } public function db_connect() { public function delete($where) { public function insert($data) { public function read($where) { public function update($where) {

HERE,

“class … extends DBCommonMethods” use the methods in the DBCommonMethods

“… implements DBInterface” ensures that the class provides standard methods regardless of the database driver used.

Usage of the above code The code using the above class would look like this

Or

The rest of the code would be the same for both drivers such as;

<?php

Summary

Object Oriented Programming OOP is a powerful technical that models applications after real world objects

A class is a representation of real world objects with properties and methods

The three basic principles of OOP are;

Encapsulation

Inheritance

Polymorphism

You're reading Php Object Oriented Programming (Oops) Concept Tutorial With Example

Restful Web Services Tutorial: What Is Rest Api With Example

What is Restful Web Services?

Restful Web Services is a lightweight, maintainable, and scalable service that is built on the REST architecture. Restful Web Service, expose API from your application in a secure, uniform, stateless manner to the calling client. The calling client can perform predefined operations using the Restful service. The underlying protocol for REST is HTTP. REST stands for REpresentational State Transfer.

In this REST API tutorial, you will learn-

RESTful Key Elements

REST Web services have really come a long way since its inception. In 2002, the Web consortium had released the definition of WSDL and SOAP web services. This formed the standard of how web services are implemented.

In 2004, the web consortium also released the definition of an additional standard called RESTful. Over the past couple of years, this standard has become quite popular. And is being used by many of the popular websites around the world which include Facebook and Twitter.

The key elements of a RESTful implementation are as follows:

Request Headers – These are additional instructions sent with the request. These might define the type of response required or the authorization details.

Request Body – Data is sent with the request. Data is normally sent in the request when a POST request is made to the REST web services. In a POST call, the client actually tells the REST web services that it wants to add a resource to the server. Hence, the request body would have the details of the resource which is required to be added to the server.

Response Status codes – These codes are the general codes which are returned along with the response from the web server. An example is the code 200 which is normally returned if there is no error when returning a response to the client.

Restful Methods

The key elements of a RESTful implementation are as follows:

The below diagram shows mostly all the verbs (POST, GET, PUT, and DELETE) and an REST API example of what they would mean.

POST – This would be used to create a new employee using the RESTful web service

GET – This would be used to get a list of all employee using the RESTful web service

PUT – This would be used to update all employee using the RESTful web service

DELETE – This would be used to delete all employee using the RESTful services

The following actions would have their respective meanings.

POST – This would not be applicable since we are fetching data of employee 1 which is already created.

GET – This would be used to get the details of the employee with Employee no as 1 using the RESTful web service

PUT – This would be used to update the details of the employee with Employee no as 1 using the RESTful web service

DELETE – This is used to delete the details of the employee with Employee no as 1

Why Restful

Restful mostly came into popularity due to the following reasons:

1. Heterogeneous languages and environments – This is one of the fundamental reasons which is the same as we have seen for SOAP as well.

It enables web applications that are built on various programming languages to communicate with each other

With the help of Restful services, these web applications can reside on different environments, some could be on Windows, and others could be on Linux.

But in the end, no matter what the environment is, the end result should always be the same that they should be able to talk to each other. Restful web services offer this flexibility to applications built on various programming languages and platforms to talk to each other.

The below picture gives an example of a web application which has a requirement to talk to other applications such Facebook, Twitter, and Google.

Now if a client application had to work with sites such as Facebook, Twitter, etc. they would probably have to know what is the language Facebook, Google and Twitter are built on, and also on what platform they are built on.

Based on this, we can write the interfacing code for our web application, but this could prove to be a nightmare.

Facebook, Twitter, and Google expose their functionality in the form of Restful web services. This allows any client application to call these web services via REST.

2. The event of Devices – Nowadays, everything needs to work on Mobile devices, whether it be the mobile device, the notebooks, or even car systems.

Can you imagine the amount of effort to try and code applications on these devices to talk with normal web applications? Again Restful API’s can make this job simpler because as mentioned in point no 1, you really don’t need to know what is the underlying layer for the device.

3. Finally is the event of the Cloud – Everything is moving to the cloud. Applications are slowly moving to cloud-based systems such as in Azure or Amazon. Azure and Amazon provide a lot of API’s based on the Restful architecture. Hence, applications now need to be developed in such a way that they are made compatible with the Cloud. So since all Cloud-based architectures work on the REST principle, it makes more sense for web services to be programmed on the REST services based architecture to make the best use of Cloud-based services.

Restful Architecture

An application or architecture considered RESTful or REST-style has the following characteristics

1. State and functionality are divided into distributed resources – This means that every resource should be accessible via the normal HTTP commands of GET, POST, PUT, or DELETE. So if someone wanted to get a file from a server, they should be able to issue the GET request and get the file. If they want to put a file on the server, they should be able to either issue the POST or PUT request. And finally, if they wanted to delete a file from the server, they can issue the DELETE request.

2. The architecture is client/server, stateless, layered, and supports caching

Client-server is the typical architecture where the server can be the web server hosting the application, and the client can be as simple as the web browser.

Stateless means that the state of the application is not maintained in REST. For example, if you delete a resource from a server using the DELETE command, you cannot expect that delete information to be passed to the next request.

RESTFul Principles and Constraints

The REST architecture is based on a few characteristics which are elaborated below. Any RESTful web service has to comply with the below characteristics in order for it to be called RESTful. These characteristics are also known as design principles which need to be followed when working with RESTful based services.

RESTFul Client-Server

This is the most fundamental requirement of a REST based architecture. It means that the server will have a RESTful web service which would provide the required functionality to the client. The client send’s a request to the web service on the server. The server would either reject the request or comply and provide an adequate response to the client.

Stateless

The concept of stateless means that it’s up to the client to ensure that all the required information is provided to the server. This is required so that server can process the response appropriately. The server should not maintain any sort of information between requests from the client. It’s a very simple independent question-answer sequence. The client asks a question, the server answers it appropriately. The client will ask another question. The server will not remember the previous question-answer scenario and will need to answer the new question independently.

Cache

The Cache concept is to help with the problem of stateless which was described in the last point. Since each server client request is independent in nature, sometimes the client might ask the server for the same request again. This is even though it had already asked for it in the past. This request will go to the server, and the server will give a response. This increases the traffic across the network. The cache is a concept implemented on the client to store requests which have already been sent to the server. So if the same request is given by the client, instead of going to the server, it would go to the cache and get the required information. This saves the amount of to and fro network traffic from the client to the server.

Layered System

The concept of a layered system is that any additional layer such as a middleware layer can be inserted between the client and the actual server hosting the RESTFul web service (The middleware layer is where all the business logic is created. This can be an extra service created with which the client could interact with before it makes a call to the web service.). But the introduction of this layer needs to be transparent so that it does not disturb the interaction between the client and the server.

Interface/Uniform Contract

This is the underlying technique of how RESTful web services should work. RESTful basically works on the HTTP web layer and uses the below key verbs to work with resources on the server

POST – To create a resource on the server

GET – To retrieve a resource from the server

PUT – To change the state of a resource or to update it

DELETE – To remove or delete a resource from the server

Create your first Restful web service in ASP.NET

Now in this REST API tutorial, we will learn how to create a Restful web service in ASP.NET:

Web services can be created in a variety of languages. Many integrated development environments can be used to create REST-based services.

In this RESTful API example, we are going to create our REST application in .Net using Visual Studio. In our example, for Restful web services we are going to emulate the following REST service example.

We are going to have a Restful web service which will work on the below set of data.

The below set of data represents an REST API example of having a company which exposes the Tutorial’s they have based on the Tutorialid.

Tutorialid TutorialName

0 Arrays

1 Queues

2 Stacks

In our REST API tutorial example, we are going to implement the below Restful Verbs.

GET Tutorial – When a client invokes this Restful API, they will be given the entire set of Tutorials available from the web service.

GET Tutorial/Tutorialid – When a client invokes this Restful API, they will be given the Tutorial name based on the Tutorialid sent by the client.

POST Tutorial/Tutorialname – When a client invokes this Restful API, the client will submit a request to insert a Tutorialname. The web service will then add the submitted Tutorial name to the collection.

DELETE Tutorial/Tutorialid– When a client invokes this Restful API, the client will submit a request to delete a Tutorialname based on the Tutorialid. The web service will then delete the submitted Tutorial name from the collection.

Let’s follow the below steps in this RESTful API tutorial to create our first RESTful web services, which carries out the above implementation.

How to Create Your First Resful Web Service

Step 2) Enter project name and location.

Ensure to first choose the RESTful web services C# web template of chúng tôi Web application. The project has to be of this type in order to create web services project. By choosing this options, Visual Studio will then carry out the necessary steps to add required files which are required by any web-based application.

Give a name for your project which in our case has been given as “Webservice.REST”.

Then ensure to give a location, where the project files will be stored.

Once done you will see the project file created in your solution explorer in Visual Studio 2013.

The next step is to create the web service file which is going to have the RESTful web service

In this step,

In the dialog box which appears, you need to perform the following

Choose the option of WCF Service (Ajax-enabled) – Choose a file of this type, it causes the Visual studio to add some basic code which helps one create a RESTful web service. WCF stands for Windows Communication Foundation. WCF is a library for applications of various platforms or the same platform to communicate over the various protocols such as TCP, HTTP, HTTPS. Ajax basically is Asynchronous JavaScript and XML. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes.

Next give a name for the service which is TutorialService in our case.

The next step is to actually make a configuration change to enable this project to complete work with RESTful web services. This requires to make a change to the file called Web.config. This file appears in the same window as the Webservice project file. The file Web.config contains all configurations that make the web application work as it should. The change being made actually allows the application to send and receive data as a pure RESTful web service.

The next step in this RESTful API tutorial is to add our code for implementation. All of the below-mentioned code has to be written in the chúng tôi file

The first bit is to add code to represent our data which will be used in our program. So we are going to have a list of string variables with values of “Arrays”, “Queues” and “Stacks”. This will represent the tutorials name available through our hosting web service.

namespace Webservice.REST { [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed public class TutorialService { (new String[] {"Arrays","Queues","Stacks"});

Next we will define the code for our GET method. This code will also reside in the same chúng tôi file. This code will run whenever we call the service from our browser.

The below method will be used to fulfill the below-mentioned scenario

If a user wants a list of all Tutorials available, then the below code would need to be written to accomplish this.

[WebGet(UriTemplate="/Tutorial")] public String GetAllTutorial() { int count = 1st.Count; String TutorialList = ""; for (int i = 0; i < count; i++) TutorialList = TutorialList + lst[i] + ","; return TutorialList; }

Code Explanation:-

This section of code is used to go through our list of strings in the ‘lst’ variable and return all of them to the calling program.

The code below ensures that if a GET call is made to the Tutorial Service with a Tutorial id, then it would return the corresponding Tutorial Name based on the Tutorial id.

[WebGet (UriTemplate = "/Tutorial/{Tutorialid}")] public String GetTutorialbyID(String Tutorialid) { int pid; Int32.TryParse(Tutorialid, out pid); return lst[pid]; }

Code Explanation:-

This section of code is used to return the “Tutorial name” which has the Tutorial id passed to the web method.

By default, what needs to be remembered is that whatever is passed to the URL in the browser is a string.

But you have to remember that the Index to our list has to be an integer, so we are adding the necessary code to first convert the Tutorialid to an Integer and then use it to access the index position in our list and

Then return the value to the calling program accordingly.

The next step is to write up the code for our POST method. This method will be invoked whenever we want to add a string value to our list of Tutorials via the POST method. For example, if you wanted to add the Tutorial name of “Software Testing” then you would need to use the POST method.

Code Explanation:-

The first line is the ‘WebInvoke’ attribute which has been attached to our method. This allows the method to be invoked via the POST call. The RequestFormat and ResponseFormat attribute have to be mentioned as JSON, since when posting values to a RESTFul web service, the values have to be in this format.

The second line of code is used to add the string value passed via the POST call to our existing list of Tutorial strings.

Finally we are going to add our method to handle the DELETE operation. This method will be invoked whenever we want to delete an existing string value from our list of Tutorials via the DELETE method.

[WebInvoke(Method = "DELETE", RequestFormat = WebMessageFormat.Json, UriTemplate = "/Tutorial/{Tutorialid}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)] public void DeleteTutorial(String Tutorialid) { int pid; Int32.TryParse(Tutorialid, out pid); 1st.RemoveAt(pid); }

Code Explanation:-

The first line is the ‘WebInvoke’ attribute which has been attached to our method. This allows the method to be invoked via the POST call. The RequestFormat and ResponseFormat attribute have to be mentioned as JSON, since when posting values to a RESTFul web service, the values have to be in this format. Note that the Method parameter is being set to “DELETE.” This means that whenever we issue the DELETE verb, this method will be invoked.

The second line of code is used to take the Tutorialid sent via the DELETE call and subsequently delete that id from our list. (The Int32 function in code is used to convert the Tutorial ID from a string variable to an integer).

Running your first Restful web service

Now that we have created our entire web service in the above section. Let’s see how we can run the Tutorial service so that it can be invoked from any client.

To run the web service, please follow the below steps

Step 2) Choose the menu option ‘Set as StartUp Project’. This will ensure that this project is run when Visual Studio runs the entire solution

Output:-

When the project is run, you can browse to your chúng tôi section, and you will get the below output.

In the above output,

You can see that the browser is invoking the ‘GET’ verb and executing the ‘GetAllTutorial’ method in the web service. This module is used to display all the Tutorials exposed by our web service.

Testing your first Restful web service

In the above section, we have already seen how to use the browser to execute the ‘GET’ verb and invoke the ‘GetAllTutorial.’

Let’s now use the browser to execute the following use case scenario.

GET Tutorial/Tutorialid – When a client invokes this Restful API, they will be given the Tutorial name based on the Tutorialid sent by the client

In your browser, append the string /1 after the Tutorial word in the URL. If you hit the enter button, you will get the below output

Now you will see the output of Queues which actually corresponds to the number 1 in our list of Tutorial Strings. This means that the ‘GetTutorialbyID’ method is now being invoked from our Webservice. It also shows that the value of 1 is being passed successfully via the browser to our web service and to our method and that is why we are getting the correct corresponding value of “Queues” in the browser.

Next let’s consume our web service by executing the below scenario. For this, you need to install the tool called “Fiddler” which is a free downloadable tool from the site.

POST Tutorial/Tutorialname – When a client invokes this Restful API, the client will submit a request to insert a Tutorialname. The web service will then add the submitted Tutorial name to the collection.

Run the Filddler tool and perform the below steps;

Go to the composer section. This is used to create requests which can be submitted to any webapplication.

Make sure the Content-Type is marked as application/json. Remember that our POST request method in our Web service only accepts json style data so we need to ensure this is specified when we are sending a request to our application.

Finally, we need to enter our data. Remember that our method for POST accepts a parameter called ‘str.’ So here we are specifying that we want to add a value called “Trees” to our collection of Tutorial names and ensure that it is tagged to the str variable name.

Now, when we browse to the Tutorial URL to show all the strings in our Tutorial list, you will now see the value of “Trees” is also present. This shows that the POST request to the web service was successfully executed and that it was successfully added to our Tutorial List.

Next let’s consume our web service by executing the below scenario. For this also we need to use the fiddler tool

DELETE Tutorial/Tutorialid- When a client invokes this Restful API, the client will submit a request to delete a Tutorialname based on the Tutorialid. The web service will then delete the submitted Tutorial name from the collection.

Run the Filddler tool and perform the below steps

Go to the composer section. This is used to create requests which can be submitted to any webapplication.

Now, when we browse to the Tutorial URL to show all the strings in our Tutorial list, you will notice that the value of “Queues” is no longer present.

This shows that the DELETE request to the web service was successfully executed. The element at index no 1 in our list of Tutorial strings was successfully deleted.

Summary

REST stands for REpresentational State Transfer. REST is used to build web services that are lightweight, maintainable, and scalable in nature.

More and more applications are moving to the Restful architecture. This is because there are a lot of people now using mobile devices and a wider variety of applications moving to the cloud.

The main aspects of REST are the resources which reside on the server and the verbs of GET, POST, PUT and DELETE, which can be used to work with these resources.

Visual Studio chúng tôi can be used to create Restful web services.

When Testing web services for POST and PUT, you need to use another tool called fiddler which can be used to send the POST and PUT request to the server.

Yield In Python Tutorial: Generator & Yield Vs Return Example

What is Python yield?

The yield keyword in python works like a return with the only

difference is that instead of returning a value, it gives back a generator object to the caller.

When a function is called and the thread of execution finds a yield keyword in the function, the function execution stops at that line itself and it returns a generator object back to the caller.

In this Python tutorial, you will learn:

Syntax yield expression Description

Python yield returns a generator object. Generators are special functions that have to be iterated to get the values.

The yield keyword converts the expression given into a generator function that gives back a generator object. To get the values of the object, it has to be iterated to read the values given to the yield.

Example: Yield Method

Here is a simple example of yield. The function testyield() has a yield keyword with the string “Welcome to Guru99 Python Tutorials”. When the function is called, the output is printed and it gives a generator object instead of the actual value.

def testyield(): yield "Welcome to Guru99 Python Tutorials" output = testyield() print(output)

Output:

The output given is a generator object, which has the value we have given to yield.

But we are not getting the message we have to given to yield in output!

To print the message given to yield will have to iterate the generator object as shown in the example below:

def testyield(): yield "Welcome to Guru99 Python Tutorials" output = testyield() for i in output: print(i)

Output

Welcome to Guru99 Python Tutorials What are Generators in Python?

Generators are functions that return an iterable generator object. The values from the generator object are fetched one at a time instead of the full list together and hence to get the actual values you can use a for-loop, using next() or list() method.

Using Generator function

You can create generators using generator function and using generator expression.

A generator function is like a normal function, instead of having a return value it will have a yield keyword.

To create a generator function you will have to add a yield keyword. The following examples shows how to create a generator function.

def generator(): yield "H" yield "E" yield "L" yield "L" yield "O" test = generator() for i in test: print(i)

Output:

H E L L O Difference between Normal function v/s Generator function.

Let us understand how a generator function is different from a normal function.

There are 2 functions normal_test() and generator_test().

Both the functions are suppose to return back the string “Hello World”. The normal_test() is using return and generator_test() is using yield.

# Normal function def normal_test(): return "Hello World" #Generator function def generator_test(): yield "Hello World" print(normal_test()) #call to normal function print(generator_test()) # call to generator function

Output:

Hello World

This is the main difference between a generator function and a normal function. Now to get the value from the generator object we need to either use the object inside for loop or use next() method or make use of list().

print(next(generator_test())) # will output Hello World

One more difference to add to normal function v/s generator function is that when you call a normal function the execution will start and stop when it gets to return and the value is returned to the caller. So when the execution starts you cannot stop the normal function in between and it will only stop when it comes across return keyword.

But in case of generator function once the execution starts when it gets the first yield it stops the execution and gives back the generator object. You can use the generator object to get the values and also, pause and resume back as per your requirement.

How to read the values from the generator?

You can read the values from a generator object using a list(), for-loop and using next() method.

Using : list()

A list is an iterable object that has its elements inside brackets.Using list() on a generator object will give all the values the generator holds.

def even_numbers(n): for x in range(n): if (x%2==0): yield x num = even_numbers(10) print(list(num))

Output:

[0, 2, 4, 6, 8] Using : for-in

In the example, there is a function defined even_numbers() that will give you all even numbers for the n defined. The call to the function even_numbers() will return a generator object, that is used inside for-loop.

Example:

def even_numbers(n): for x in range(n): if (x%2==0): yield x num = even_numbers(10) for i in num: print(i)

Output:

0 2 4 6 8 Using next()

The next() method will give you the next item in the list, array, or object. Once the list is empty, and if next() is called, it will give back an error with stopIteration signal. This error, from next() indicates that there are no more items in the list.

def even_numbers(n): for x in range(n): if (x%2==0): yield x num = even_numbers(10) print(next(num)) print(next(num)) print(next(num)) print(next(num)) print(next(num)) print(next(num))

Output:

0 2 4 6 8 Traceback (most recent call last): print(next(num)) StopIteration Generators are one-time Use

Incase of generators they are available for use only once. If you try to use them again, it will be empty.

For example:

def even_numbers(n): for x in range(n): if (x%2==0): yield x num = even_numbers(10) for i in num: print(i) print("n") print("Calling the generator again: ", list(num))

Output:

0 2 4 6 8 Calling the generator again: []

In case you want the output to be used again, you will have to make the call to function again.

Example: Generators and yield for Fibonacci Series

The following example shows how to use generators and yield in Python. The example will generate the Fibonacci series.

def getFibonnaciSeries(num): c1, c2 = 0, 1 count = 0 while count < num: yield c1 c3 = c1 + c2 c1 = c2 c2 = c3 count += 1 fin = getFibonnaciSeries(7) print(fin) for i in fin: print(i)

Output:

0 1 1 2 3 5 8

Example: Calling Function with Yield

In this example will see how to call a function with yield.

The below example has a function called test() that returns the square of the given number. There is another function called getSquare() that uses test() with yield keyword. The output gives the square value for given number range.

def test(n): return n*n def getSquare(n): for i in range(n): yield test(i) sq = getSquare(10) for i in sq: print(i)

Output:

0 1 4 9 16 25 36 49 64 81 When to use Yield Instead of Return in Python

Python3 Yield keyword returns a generator to the caller and the execution of the code starts only when the generator is iterated.

A return in a function is the end of the function execution, and a single value is given back to the caller.

Here, is the situation when you should use Yield instead of Return

Use yield instead of return when the data size is large

Yield is the best choice when you need your execution to be faster on large data sets

Use yield when you want to return a big set of values to the calling function

Yield is an efficient way of producing data that is big or infinite.

Yield vs. Return

Here, are the differences between Yield and Return

Yield Return

Yield returns a generator object to the caller, and the execution of the code starts only when the generator is iterated. A return in a function is the end of the function execution, and a single value is given back to the caller.

When the function is called and it encounters the yield keyword, the function execution stops. It returns generator object back to the caller. The function execution will start only when the generator object is executed. When the function is called, the execution starts and the value is given back to the caller if there is return keyword. The return inside the function marks the end of the function execution.

yield expression return expression

No memory is used when the yield keyword is used. The memory is allocated for the value returned.

Very useful if you have to deal with huge data size as the memory is not used. Convenient for very small data size.

The performance is better if the yield keyword is used for large data size. A lot of memory is used if the data size is huge that will hamper the performance.

Execution time is faster in case of yield for large data size. The execution time used is more as there is extra processing done in case if your data size is huge, it will work fine for small data size.

Summary:

The yield keyword in python works like a return with the only difference is that instead of returning a value, it gives back a generator function to the caller.

A generator is a special type of iterator that, once used, will not be available again. The values are not stored in memory and are only available when called.

The values from the generator can be read using for-in, list() and next() method.

The main difference between yield and return is that yield returns back a generator function to the caller and return gives a single value to the caller.

The performance is better if the yield keyword is used in comparison to return for large data size.

Complete Guide To Php References With Examples

Introduction to PHP References

PHP reference are the symbol table aliases by means of which content of one variable can be access by different names. The explicitly defined referenced variable needs to be preceded by ampersand (&) symbol. The functionality of PHP references can be explained using the analogy of Window’s shortcut. PHP references can be defined in PHP programming in various ways.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Methods to Create PHP References

Mostly used methods to create PHP references are discussed as below:

1. Using the Keyword ‘global’

In the method reference can be created using the keyword ‘global’ before the referenced variable. Declaring a reference as global variable adds the variable to $GLOBAL array and enable the user to access a global variable within the scope of the function. Basically there are two ways through which a PHP reference can be defined being declared as global variable such as:

function Function_name() { global $globalVar; } OR function Function_name() { $globalVar =& $GLOBALS["globalVar"]; }

The below code snippet is designed to demonstrate the different between the value for the same variable with respect to local scope and to global scope.

<?php function functionname() { $inputvar = "within function scope"; echo '$inputvar in global scope: ' . $GLOBALS["inputvar"] . "n"; echo '$inputvar in current scope: ' . $inputvar . "n"; } $inputvar = "Outside function scope"; $othervar= $GLOBALS["inputvar"]; functionname(); echo '$othervar : ' . $othervar . "n";

Output

Othervar is the reference set for the inputvar from GLOBAL array. It is not bound to the inputvar variable defined in the local scope of the function.

2. Using $this Variable

‘$this’ variable is default reference to the object for the function, of which, $this variable is referred.

Example

The below code demonstrates the usage of $this variable to access value of any class property from the chosen class object.

<?php class Thisclass { var $clsproperty = 300; function classmethod() { } } $clsObject = new Thisclass();

Output

The value of the clsproperty is displayed based on the value set by using $this variable.

3. Passing an Object

In PHP programming, any operation performed on a class object such as assign, return or pass, etc; the operation always is carried out with reference to the object instead of its copy.

The standard syntax to create PHP object reference is followed as below:

class ClassName { } $classObj1 = new ClassName (); $classObj2= $classObj1;

Here classObj2 object is referring to the same content contained in classObj1.

Example

<?php class Costume { public $name; public $color; function set_name($name) { } function get_name() { } function set_color($color) { } function get_color() { } } $constume1 = new Costume(); $constume2=$constume1; echo "n"; echo "n"; echo "n"; echo "n";

Output

The reference object Costume2 refers to the same values as carried within the properties name and color of the actual object Costume1.

Different Operations of PHP Programming

In PHP programming different operations are carried out with PHP references. Some of the major operations are discussed in the below session:

1. Passing by Reference

In order to enable a function to modify a variable which is defined out of its scope, the value needs to pass to the function by its reference.

Example

The below code snippet changes the value of the variable defined out of the scope of the called function using the reference to the variable.

<?php function Afunction(&$input) { $input*=10; } $outVar=5; echo "Before the function is called: ".$outVar; echo "n"; Afunction($outVar); echo "After the function is called: ".$outVar;

Output

The value of the variable outvar is changed by the function AFunction().

2. Returning References

Example

The below code snippet is designed to pass the return value from a function parent function as reference to the defined class parent class.

<?php class parentclass { public $parentvar = "I am set at parent class"; public function &parentfunction() { } } $parentobj = new parentclass; echo $newvar; echo "n"; echo $newvar;

Output

3. Unsetting PHP Reference

User can break the binding between the variable and reference using the method unset().

Example

The below code snippet demonstrates the usage of the method unset() to unbound the referenced variable firstinput from secondinput.

<?php $firstinput = "I am first input"; $secondinput =& $firstinput; echo "First input: ". $firstinput; echo"n"; echo "Second input: " . $secondinput; unset($firstinput); echo"n"; echo"n"; echo "After unsetting the reference: "; echo"n"; $firstinput = "I am set to second input"; echo"n"; echo "First input: ". $firstinput; echo"n"; echo "Second input: " . $secondinput;

Output

Conclusion

PHP references are important feature that is incorporated in PHP scripting. PHP references are not pointers as it can be described for ‘C’ which also occupy memory to create duplicate element. Rather PHP references are just different alias to refer the content from the actual variable. If copy of an object is required for an object in PHP, it can be done with the keyword ‘clone’.

Recommended Articles

This is a guide to PHP References. Here we discuss the introduction and methods to create PHP References along with different operations. You may also have a look at the following articles to learn more –

Complete Guide To Php Implode Fucntion With Examples

Introduction to PHP implode

Implode is a built-in function in PHP that links array elements. This function works similarly to bind () and is an alias. In order to unite all of the components in an array to create a string, we utilize the implode function. Hence implode function gives us the string resulting from forming array elements similar to the join() function.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

string implode(separator,array);

Separator: For a type string, this input field is optional. Before the array values are concatenated to make a string, they will first be separated using the separator parameter that is provided above. If it is left out, the empty string (“) is used as the default value.

Array: The variety that needs to be linked to create the string is specified in this field, which is required.

Return type: This implode() function returns a string as its output. From the array elements, it will return the newly joined series.

Examples of PHP implode

Below are some of the examples based on implode function,, which covers a few possible scenarios where they are or can be implemented:

Example #1

Code:

<?php $Input = array('first','string','combination'); print_r(implode($Input)); print_r("n"); print_r(implode("-",$Input));

Output:

Example #2

Code:

<?php $arr = array('string1', 'string2', 'string3'); $sep= implode(",", $arr); echo $sep; print_r("n"); var_dump(implode('check', array()));

Output:

In this example, we first declare 3 strings as part of an array “arr”. Next, we are using implode function and mentioning the comma separator to use for separating these 3 strings. We are also showing the results of using an empty array. It returns an empty string in this case, as shown.

Example #3

Code:

<?php $arr1 = array("1","2","3"); $arr2 = array("one"); $arr3 = array(); echo "array1 is: '".implode("'/'",$arr1); print_r("n"); echo "array2 is: '".implode("'-'",$arr2); print_r("n"); echo "array3 is: '".implode("','",$arr3);

Output:

Example #4

Code:

<?php $arr1 = array('One', 'Two', 'Three');

Output:

Here we are making using the array to display its elements in the form of ordered lists.

Example #5

Code:

<?php declare(strict_types=1); $arr1 = array( 'str1','str2','str3' ); echo implode( '-', $arr1 ),'.', implode( '-', $arr2 );

Output:

In this example, we can see that the implode function acts upon only the values of array elements and completely disregards its keys. Here ‘str1’, ‘str2’, ‘str3’ are the values directly declared in arr1, whereas in arr2 the keys are “1st”, “2nd” and their respective value pairs are “one”,”two” and “three”.

Example #6 <?php class Test { protected $name; public function __construct($name) { } public function __toString() { } } $arr = [ new Test('one'), new Test('two'), new Test('three') ]; echo implode('; ', $arr);

Output:

In the above example, we can see that even objects can be used alongside the implode function, but the only condition for this is that the objects should apply the toString() function as shown.

Example #7

Code:

<?php var_dump(implode('',array(true, false, false, true, true)));

Output:

It results in a different kind of output where we get the output in the form of 1’s wherever true is present, and in place of false, it outputs null i.e. empty value.

Conclusion

PHP implode() function, as shown in the above examples, can be used in various cases where there is a need to join different elements of an input array. It is a simple function with only two parameters where we specify the delimiter to be used to divide the array components.

Recommended Articles

We hope that this EDUCBA information on “PHP implode” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

List Of Golang Constants With Programming Examples

Introduction to Golang Constants

Constants in go are the variable that once assigned the value and initialize we cannot change it during the process of the running of the program life cycle. The main importance of using the constant in go language allows us to define a variable which will be fixed throughout the compilation of the program. There are broadly three types of constant in the go language they are string constants (containing string value), numeric constants (containing an integer and floating values), Boolean constant (containing true and false value). In general programming, the constants are defined at the top of the program and will be available for the whole flow of the code and its value will be the same for the cycle. In this topic, we are going to learn about Golang Constants.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

List of Constants in Golang 1. Integer Constant

Integer type constants are the constant which contains the integer value.

In any integer type constant, they contain an integer part.

We can use the == operator for comparing two integer type constants.

We can use the = operator for assignment of any integer type constant.

Example for an integer constant

In the below example we have taken two variables X and Y and these variables contain two integer numbers. Here we are performing two operations inside the example, one we are adding them printing the resultant output of them, second we are comparing these two variables and printing the output of comparison of these two integer values.

Please see the below example along with the screen of output

Code:

package main import "fmt" func main() { const X= 3 var Y = 6 var sum = X+Y fmt.Println(sum)//printing the sum of the two numbers fmt.Println(X == 3) fmt.Println(Y < X) }

Output:

2. Floating Type Constant

Floating type constants are the constant which contains the decimal value integer.

In any floating type constant they contain two parts one is the faction part value and another is the exponent part value.

We can use the == operator for comparing two floating type constants.

We can use the = operator for assignment of any floating type constant.

At the time of displaying the floating type constant we need to consider the decimal points.

Example of Floating Type constant

In the below example we have taken two variables X and Y and these variables contain two floating numbers. Here we are performing two operations inside the example, one we are adding them printing the resultant output of them, second we are comparing these two variables and printing the output of comparison of these two floating values.

Please see the below example along with the screen of output

Code:

package main import "fmt" func main() { const X= 3.4 var Y = 6.9 var sum = X+Y fmt.Println(sum) fmt.Println(X == 3.2)//It will print true or false fmt.Println(Y < X) }

3. String Constants

In Go language we can use two types of the constants one is with the single quote(‘’) and another with the double quote(“”).

We can perform all the operations on the string like string concatenation, to perform string concatenation in the language we can use + symbol. We can also use a format like +=.

Many times you will see the requirement of comparing the two strings in go language, so we can use the == operator for comparison of string.

We can simply use the = operator for operating on assignment.

Example for String Type constant

In the below example we have taken two variables X and Y and these variables contain two string values. Here we are performing two operations inside the example, one we concatenate them printing the resultant output of them, second, we are comparing these two variables and printing the output of comparison of these two strings values.

Please see the below example along with the screen of output

Code:

package main import "fmt" func main() { const X= "Ranjan" var Y = "Ajay" var greetings = X+ " " + Y greetings += "!" fmt.Println(greetings) fmt.Println(X == "Ranjan") fmt.Println(Y < X) }

Output:

4. Boolean constant

The boolean constants are very much similar to any string constants.

The main difference between string constants and boolean constants is they allow us to define two types true and false whereas in case of the string constant they are only string.

Boolean constants are used for managing some flag values like yes or no or true or false.

Example for Boolean Type constant

In the below example we are performing some operations on a boolean value, we are assigning and printing the boolean value in the go language.

Please see the below example along with the screen of output

Code:

package main import "fmt" const Py = 3.14 func main() { const boolConst = true type exampleBool bool var initialBool = boolConst var simpleBool exampleBool = boolConst fmt.Println(initialBool) fmt.Println(simpleBool) }

Output:

Conclusion

From this tutorial we learned about the basic concept of the constant in the go language and we learned about its various types. We learned with the help of the various examples of the various types of constants in the go language.

Recommended Articles

This is a guide to Golang Constants. Here we discuss the List of Constants in Golang with programming examples for better understanding. You may also have a look at the following articles to learn more –

Update the detailed information about Php Object Oriented Programming (Oops) Concept Tutorial With Example on the Cancandonuts.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!