Javascript: Oops

 

PHP What is OOP?


OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or functions that perform operations on the data, while object-oriented programming is about creating objects that contain both data and functions.

Object-oriented programming has several advantages over procedural programming:

  • OOP is faster and easier to execute
  • OOP provides a clear structure for the programs
  • OOP helps to keep the PHP code DRY “Don’t Repeat Yourself”, and makes the code easier to maintain, modify and debug
  • OOP makes it possible to create full reusable applications with less code and shorter development time

Define a Class

A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces ({}). All its properties and methods go inside the braces:

Syntax


class Fruit {
// code goes here…
}
?>

Define Objects

Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values.

Objects of a class is created using the new keyword.

Example


class Fruit {
// Properties
  public $name;
public $color;
// Methods
  function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}$apple = new Fruit();
echo $apple->get_name();
echo
;
echo $banana->get_name();
?>

PHP – The __construct Function

A constructor allows you to initialize an object’s properties upon creation of the object.

If you create a __construct() function, PHP will automatically call this function when you create an object from a class.

Example


class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}$apple = new Fruit(“Apple”);
echo $apple->get_name();
?>

Leave a Reply