Cover Image for OOPs Compound Types
189 views

OOPs Compound Types

In object-oriented programming (OOP), compound types refer to data types that can hold multiple values or elements. These compound types allow you to group related data together, making it easier to manage and work with complex data structures. The two main compound types in OOP are arrays and objects.

  1. Arrays:
    An array is a compound data type that can hold multiple values of different types in an ordered list. In PHP, arrays can be indexed (numerically or associatively) or can be used as key-value pairs. Arrays allow you to store and access multiple data elements using their respective keys or indices.

Indexed Array Example:

$numbers = array(10, 20, 30, 40);
// or, in PHP 5.4 and later, using the short array syntax:
// $numbers = [10, 20, 30, 40];

echo $numbers[0]; // Output: 10
echo $numbers[2]; // Output: 30

Associative Array Example:

$student = array(
    "name" => "John Doe",
    "age" => 25,
    "course" => "Computer Science"
);

echo $student["name"]; // Output: John Doe
echo $student["age"]; // Output: 25
  1. Objects:
    An object is a compound data type that allows you to define a custom data structure using classes. An object is an instance of a class and can contain properties (variables) and methods (functions). Objects are used to represent entities, such as real-world objects, and provide a way to encapsulate data and behavior together.

Example:

class Student {
    public $name;
    public $age;
    public $course;

    public function __construct($name, $age, $course) {
        $this->name = $name;
        $this->age = $age;
        $this->course = $course;
    }

    public function getInfo() {
        return "Name: " . $this->name . ", Age: " . $this->age . ", Course: " . $this->course;
    }
}

$student1 = new Student("John Doe", 25, "Computer Science");
echo $student1->getInfo(); // Output: Name: John Doe, Age: 25, Course: Computer Science

In this example, we define a Student class with properties name, age, and course, and a method getInfo() to retrieve the student’s information.

Arrays and objects are powerful tools in OOP, and they allow you to create sophisticated data structures and organize your code more effectively. By using compound types, you can build complex applications with structured and maintainable code.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS