How OOPs in PHP can help you

Sharing is caring!

313 Views -

OBJECT-ORIENTED PROGRAMMING IN PHP
Basic concepts in Object-Oriented Programming are-
Class-
Class is a way to bind data and associated functions together.
Simple class definitions start with the keyword class, followed by a class name, followed by a pair of curly braces that contain the definitions of the properties and methods of that class.
A class may contain its own constants, variables (called properties), and functions (called methods).
Simple class

<?php
class DemoClass
{
  // property declaration
  public $name= 'Raman';

  // method/function declaration
  public function displayVar() {
   echo $this->name;
  }
}
?>

 

New keyword-

To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases, this is a requirement).

If a string containing the name of a class is used with a new one, a new instance of that class will be created. If the class is in a namespace, its fully qualified name must be used when doing this.

creating an instance of a class

<?php
$instance = new DemoClass();

// This can also be done with a variable:
$className = 'Physics';
$instance = new $className(); // new SimpleClass()
?>

 

Object-

Access Modifiers

Inheritance

extends – Keyword

A class can inherit the methods and properties of another class by using the keyword extends in the class declaration. It is not possible to extend multiple classes; a class can only inherit from one base class.

class Shape {
public function name() {
echo "I am a shape";
}
}

class Circle extends Shape {

}

$circle = new Circle();
$circle->name(); // I am a shape

 

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.

Static class –
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can).

<?php
class Foo {
  public static function aStaticMethod() {
  // ...
  }
}

Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0
?>

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments