Call
Calling or using a class in PHP involves creating an instance of the class and then accessing its properties and methods. Here's a detailed guide on how to do this.
Step-by-Step Guide
- Define the Class:
- Define a class with properties and methods.
- Create an Instance of the Class:
- Use the new keyword to create an object (instance) of the class.
- Access Properties and Methods:
- Use the -> operator to access properties and methods of the object.
Example
Let's define a class Car and then create an instance of it and call its methods
<?php
// Step 1: Define the Class
class Car {
// Properties
public $make;
public $model;
public $year;
// Constructor
public function __construct($make, $model, $year) {
$this->make = $make;
$this->model = $model;
$this->year = $year;
}
// Methods
public function display() {
return "This car is a $this->year $this->make $this->model.";
}
public function start() {
return "The car has started.";
}
}
// Step 2: Create an Instance of the Class
$myCar = new Car("Toyota", "Corolla", 2021);
// Step 3: Access Properties and Methods
echo $myCar->display(); // Outputs: This car is a 2021 Toyota Corolla.
echo "\n"; // New line for better readability
echo $myCar->start(); // Outputs: The car has started.
?>
Explanation
Define the Class:
- class Car { ... }: This defines the Car class.
- Properties: $make, $model, $year to hold the car's make, model, and year.
- Constructor: __construct($make, $model, $year) to initialize the properties when a new object is created.
- Methods: display() and start() to provide functionality to the class.
Create an Instance:
- $myCar = new Car("Toyota", "Corolla", 2021);: This creates a new instance of the Car class, passing the make, model, and year to the constructor.
Access Properties and Methods:
- echo $myCar->display();: Calls the display method of the $myCar object.
- echo $myCar->start();: Calls the start method of the $myCar object.
Additional Example
You can also define a class with more properties and methods to demonstrate different functionalities:
<?php
class Person {
// Properties
public $firstName;
public $lastName;
public $age;
// Constructor
public function __construct($firstName, $lastName, $age) {
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->age = $age;
}
// Methods
public function getFullName() {
return "$this->firstName $this->lastName";
}
public function isAdult() {
return $this->age >= 18 ? "Adult" : "Not an Adult";
}
}
// Create an instance of the class
$person = new Person("John", "Doe", 25);
// Access the methods
echo $person->getFullName(); // Outputs: John Doe
echo "\n"; // New line for better readability
echo $person->isAdult(); // Outputs: Adult
?>
Summary
- Define the Class: Use class ClassName { ... }.
- Create an Instance: Use new ClassName(parameters);.
- Access Properties and Methods: Use $object->property and $object->method().