Functions in PHP

Last updated on May 31 2022
Aridam Das

Table of Contents

Functions in PHP

PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.

You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.

There are two parts which should be clear to you −

  • Creating a PHP Function
  • Calling a PHP Function

In fact you hardly need to create your own PHP function because there are already more than 1000 of built-in library functions created for different area and you just need to call them according to your requirement.

Creating PHP Function

Its very easy to create your own PHP function. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it. Following example creates a function called writeMessage() and then calls it just after creating it.

Note that while creating a function its name should start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below −

 

<html>

  

   <head>

      <title>Writing PHP Function</title>

   </head>

  

   <body>

     

      <?php

         /* Defining a PHP Function */

         function writeMessage() {

            echo "You are really a nice person, Have a nice time!";

         }

        

         /* Calling a PHP Function */

         writeMessage();

      ?>

     

   </body>

</html>

This will display following result −

You are really a nice person, Have a nice time!

PHP Functions with Parameters

PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like. These parameters work like variables inside your function. Following example takes two integer parameters and add them together and then print them.

 

<html>

  

   <head>

      <title>Writing PHP Function with Parameters</title>

   </head>

  

   <body>

  

      <?php

         function addFunction($num1, $num2) {

            $sum = $num1 + $num2;

            echo "Sum of the two numbers is : $sum";

         }

        

         addFunction(10, 20);

      ?>

     

   </body>

</html>

This will display following result −

Sum of the two numbers is : 30

Passing Arguments by Reference

It is possible to pass arguments to functions by reference. This means that a reference to the variable is manipulated by the function rather than a copy of the variable’s value.

Any changes made to an argument in these cases will change the value of the original variable. You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition.

Following example depicts both the cases.

 

<html>

  

   <head>

      <title>Passing Argument by Reference</title>

   </head>

  

   <body>

     

      <?php

         function addFive($num) {

            $num += 5;

         }

        

         function addSix(&$num) {

            $num += 6;

         }

        

         $orignum = 10;

         addFive( $orignum );

        

         echo "Original Value is $orignum<br />";

        

         addSix( $orignum );

         echo "Original Value is $orignum<br />";

      ?>

     

   </body>

</html>

This will display following result −

Original Value is 10

Original Value is 16

PHP Functions returning value

A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.

You can return more than one value from a function using return array(1,2,3,4).

Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function.

 

<html>

  

   <head>

      <title>Writing PHP Function which returns value</title>

   </head>

  

   <body>

  

      <?php

         function addFunction($num1, $num2) {

            $sum = $num1 + $num2;

            return $sum;

         }

         $return_value = addFunction(10, 20);

        

         echo "Returned value from the function : $return_value";

      ?>

     

   </body>

</html>

This will display following result −

Returned value from the function : 30

Setting Default Values for Function Parameters

You can set a parameter to have a default value if the function’s caller doesn’t pass it.

Following function prints NULL in case use does not pass any value to this function.

 

<html>

  

   <head>

      <title>Writing PHP Function which returns value</title>

   </head>

  

   <body>

     

      <?php

         function printMe($param = NULL) {

            print $param;

         }

        

         printMe("This is test");

         printMe();

      ?>

     

   </body>

</html>

 

Dynamic Function Calls

It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Following example depicts this behaviour.

 

<html>

  

   <head>

      <title>Dynamic Function Calls</title>

   </head>

  

   <body>

      

      <?php

         function sayHello() {

            echo "Hello<br />";

         }

        

         $function_holder = "sayHello";

         $function_holder();

      ?>

     

   </body>

</html>

This will display following result −

Hello

 

PHP – GET & POST Methods

There are two ways the browser client can send information to the web server.

  • The GET Method
  • The POST Method

Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand.

name1=value1&name2=value2&name3=value3

Spaces are removed and replaced with the + character and any other nonalphanumeric characters are replaced with a hexadecimal values. After the information is encoded it is sent to the server.

The GET Method

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character.

http://www.test.com/index.htm?name1=value1&name2=value2

  • The GET method produces a long string that appears in your server logs, in the browser’s Location: box.
  • The GET method is restricted to send upto 1024 characters only.
  • Never use GET method if you have password or other sensitive information to be sent to the server.
  • GET can’t be used to send binary data, like images or word documents, to the server.
  • The data sent by GET method can be accessed using QUERY_STRING environment variable.
  • The PHP provides $_GET associative array to access all the sent information using GET method.

Try out following example by putting the source code in test.php script.

<?php

   if( $_GET["name"] || $_GET["age"] ) {

      echo "Welcome ". $_GET['name']. "<br />";

      echo "You are ". $_GET['age']. " years old.";

     

      exit();

   }

?>

<html>

   <body>

  

      <form action = "<?php $_PHP_SELF ?>" method = "GET">

         Name: <input type = "text" name = "name" />

         Age: <input type = "text" name = "age" />

         <input type = "submit" />

      </form>

     

   </body>

</html>

It will produce the following result −

The POST Method

The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.

  • The POST method does not have any restriction on data size to be sent.
  • The POST method can be used to send ASCII as well as binary data.
  • The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.
  • The PHP provides $_POST associative array to access all the sent information using POST method.

Try out following example by putting the source code in test.php script.

<?php

   if( $_POST["name"] || $_POST["age"] ) {

      if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {

         die ("invalid name and name should be alpha");

      }

      echo "Welcome ". $_POST['name']. "<br />";

      echo "You are ". $_POST['age']. " years old.";

     

      exit();

   }

?>

<html>

   <body>

  

      <form action = "<?php $_PHP_SELF ?>" method = "POST">

         Name: <input type = "text" name = "name" />

         Age: <input type = "text" name = "age" />

         <input type = "submit" />

      </form>

  

   </body>

</html>

It will produce the following result −

The $_REQUEST variable

The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies.

The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.

Try out following example by putting the source code in test.php script.

<?php

   if( $_REQUEST["name"] || $_REQUEST["age"] ) {

      echo "Welcome ". $_REQUEST['name']. "<br />";

      echo "You are ". $_REQUEST['age']. " years old.";

      exit();

   }

?>

<html>

   <body>

     

      <form action = "<?php $_PHP_SELF ?>" method = "POST">

         Name: <input type = "text" name = "name" />

         Age: <input type = "text" name = "age" />

         <input type = "submit" />

      </form>

     

   </body>

</html>

Here $_PHP_SELF variable contains the name of self script in which it is being called.

It will produce the following result −

So, this brings us to the end of blog. This Tecklearn ‘Functions in PHP’ blog helps you with commonly asked questions if you are looking out for a job in PHP Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/java-and-jee-training/

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

  • Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
  • Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
  • Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

  • Java Fundamentals
  • Introduction to Java Basics
  • Features of Java
  • Various components of Java language
  • Benefits of Java over other programming languages
  • Key Benefits of Java

Installation and IDE’s for Java Programming Language

  • Installation of Java
  • Setting up of Eclipse IDE
  • Components of Java Program
  • Editors and IDEs used for Java Programming
  • Writing a Simple Java Program

Data Handling and Functions

  • Data types, Operations, Compilation process, Class files, Loops, Conditions
  • Using Loop Constructs
  • Arrays- Single Dimensional and Multi-Dimensional
  • Functions
  • Functions with Arguments

OOPS in Java: Concept of Object Orientation

  • Object Oriented Programming in Java
  • Implement classes and objects in Java
  • Create Class Constructors
  • Overload Constructors
  • Inheritance
  • Inherit Classes and create sub-classes
  • Implement abstract classes and methods
  • Use static keyword
  • Implement Interfaces and use it

Polymorphism, Packages and String Handling

  • Concept of Static and Run time Polymorphism
  • Function Overloading
  • String Handling –String Class
  • Java Packages

Exception Handling and Multi-Threading

  • Exception handling
  • Various Types of Exception Handling
  • Introduction to multi-threading in Java
  • Extending the thread class
  • Synchronizing the thread

File Handling in Java

  • Input Output Streams
  • io Package
  • File Handling in Java

Java Collections

  • Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
  • Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
  • Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

  • Introduction to SQL: Connect, Insert, Update, Delete, Select
  • Introduction to JDBC and Architecture of JDBC
  • Insert/Update/Delete/Select Operations using JDBC
  • Batch Processing Transaction
  • Management: Commit and Rollback

Java Enterprise Edition – Servlets

  • Introduction to J2EE
  • Client Server architecture
  • URL, Port Number, Request, Response
  • Need for servlets
  • Servlet fundamentals
  • Setting up a web project in Eclipse
  • Configuring and running the web app with servlets
  • GET and POST request in web application with demo
  • Servlet lifecycle
  • Servlets Continued
  • Session tracking and filter
  • Forward and include Servlet request dispatchers

Java Server Pages (JSP)

  • Fundamentals of Java Server Page
  • Writing a code using JSP
  • The architecture of JSP
  • JSP Continued
  • JSP elements: Scriptlets, expressions, declaration
  • JSP standard actions
  • JSP directives
  • Introduction to JavaBeans
  • ServletConfig and ServletContext
  • Servlet Chaining
  • Cookies Management
  • Session Management

Hibernate

  • Introduction to Hibernate
  • Introduction to ORM
  • ORM features
  • Hibernate as an ORM framework
  • Hibernate features
  • Setting up a project with Hibernate framework
  • Basic APIs needed to do CRUD operations with Hibernate
  • Hibernate Architecture

POJO (Plain Old Java Object)

  • POJO (Plain Old Java Object)
  • Persistent Objects
  • Lifecycle of Persistent Object

Spring

  • Introduction to Spring
  • Spring Fundamentals
  • Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

 

 

 

0 responses on "Functions in PHP"

Leave a Message

Your email address will not be published. Required fields are marked *