// Define a Person class
class Person {
// Private property to store the person's name
private $name;
// Constructor to initialize the person's name
public function __construct($name) {
$this->name = $name;
}
// Method to greet the person
public function greet() {
return 'Hello, my name is ' . $this->name;
}
}
// Create an instance of the Person class with the name 'Alice'
$person = new Person('Alice');
// Call the greet method and echo the result
echo $person->greet();
code
PHP Class and Object Example
This PHP code defines a Person class with a private property ($name), a constructor to initialize the name, and a greet method to generate a greeting. An instance of the class is created with the name 'Alice', and the greet method is called and echoed. The comments provide explanations for each part of the code.
Class
Method
Constructor
Object-Oriented Programming