Understanding Classes and ObjectsClasses and objects are the two main aspects of object-oriented programming. A class is a self-contained, independent collection of variables and functions which work together to perform one or more specific tasks, while objects are individual instances of a class.

On how? please follow this method in complete process of creating class in PHP

Step 1:

Create two PHP pages:

  • index.php
  • class_lib.php

Object Oriented Programming (OOP) is all about creating modular code, so our object oriented PHP code will be contained in dedicated files that we will then insert into our normal PHP page using php ‘includes’.

in class_lib.php file is all our Object Oriented PHP code.

Syntax:

<?php
class classname{ 
  // code goes here...
}
?>

Example Code:

<?php
class name{  // name is the class function name
  // code goes here...
}
?>

Step 2:

Now we can add Method;

Method is actually a function used in the context of a class/object. When you create a function outside of a class/object, you can call it a function but when you create a function inside a class, you can call it a method;

Syntax:

<?php
class classname{
  // Methods
  function Methodname() {
   
  }
}
?>

Example Code:

<?php
class name{  // name is the class function name
  
  function set_name()
  {

  }

}
?>

Step 3:

Now we can add Properties;

Classes can have variables within it. Those variables are called properties. A property is a normal PHP variable which is in any data type (integer, string, array, object, etc). In classes, before declaring a variable, we should add the visibility keyword to define where the variable is available.

Example:

<?php
class name{
  // Properties
  public $name;

  // Methods
  function set_name($name)
  {
     
  }
}
?>

Next Step 4:

We well make a Set and Get method in Class function;

<?php
class name{
  // Properties
  public $name;

  // Methods
  function set_name($name)
  {
      $this->name = $name;
  }
  // Methods
  function get_name()
  {
     return $this->name;
  }
}
?>

Next Step 4:

Now we proceed to index.php file

in index.php file we need to declare class_lib.php file to call the class and method function of the class;

Example.:

<?php
 include 'class_lib.php'; // this is how to include the other file so that you can use the file functionality
 $func = new name(); // and also this is how to declare the class;

?>

Next Step 5:

We need to set the $name and Get also the value of the $name;

<?php
 include 'class_lib.php'; // this is how to include the other file so that you can use the file functionality
 $func = new name(); // and also this is how to declare the class;

$func->set_name("Jave"); // this is how to set
$name = $func->get_name(); // this is how to get

echo "My name " . $name ;  // this how to display the result

?>


Example Source Code;

2 Replies to “How to make a Class Function in PHP”

Leave a Reply

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