B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP PHP OOPs (Object-Oriented Programming) | LiveCodeProgramming

PHP OOPs (Object-Oriented Programming)

OOPs in PHP allows you to structure your code using objects and classes, making it modular and reusable.

PHP में OOPs के जरिए आप अपने कोड को classes और objects की मदद से modular और reusable बना सकते हैं।

1. Class and Object

Define a class and create an object from it.

एक class बनाएँ और उससे object बनाएं।

<?php
class Student {
  public $name;
}

$obj = new Student();
$obj->name = "Rahul";
echo $obj->name;
?>
Rahul

2. Constructor

Use a constructor to initialize the object with data.

Object को initialize करने के लिए constructor का प्रयोग करें।

<?php
class Student {
  public $name;
  function __construct($n) {
    $this->name = $n;
  }
  function greet() {
    return "Hello, $this->name!";
  }
}

$obj = new Student("Aryan");
echo $obj->greet();
?>
Hello, Aryan!

3. Inheritance

One class can inherit properties and methods from another class.

एक class दूसरी class से properties और methods को inherit कर सकती है।

<?php
class Person {
  public $name;
  function __construct($name) {
    $this->name = $name;
  }
}

class Student extends Person {
  function sayHi() {
    return "Hi, I am $this->name";
  }
}

$obj = new Student("Ravi");
echo $obj->sayHi();
?>
Hi, I am Ravi