Browse By

Function and class and basics of OOPs in PHP

Spread the love

What is OOPs?

Object-Oriented Programming (PHP OOP), is a type of programming language principle added to php5, Being a programmer / Developer one should follow the concept of “Think Twice and write once“. This is something called re-usability of code.

OOPs can be achieved by using class and objects.

what is function?

A bit of code which can be used multiple time but it is not being achieved by object.eg:-

<?php
function my_first_function($var = null)
{
    if($var == null)
    {
      echo "without argument";
    }else{
      echo $var;
    }
}

//this is how you can use this function.
my_first_function();   //Output:  without argument
my_first_function("My name is Joe");  // OutPut:  My name is Joe

?>
function can be with parameter/argument or it can be with argument or it can be argument with default value.
We need not to create any object to achieve functions value.

what is class?

class is empty container and it contains functions, variable or any bit of code. it does not occupy any memory physically. We can call it blueprint of function and member variable.

creating object of a class will assign memory to class and by using it we can achieve functions and goals of a class.

<?php
class myClass
{
   function __construct()
   {
       echo "this is constructor,"; //asap object is created it will invoke and it is called constructor.
   }
   function my_first_function($var = null)
   {
       if($var == null)
       {
           echo "without argument";
       }else{
           echo $var;
      }
   }
}
$obj = new myClass();  //this is how we can achieve class data.
$obj->my_first_function("I am joe"); //Output: this is constructor, I am joe.
?>

Leave a Reply

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